search

Home  >  Q&A  >  body text

javascript - Why can't onclick directly call a parameter-containing function but needs to be written in the form onclick=function(){fn(p)}?

JS newbie, please ask me, why can't onclick directly call the parameter-containing function and need to be written in the form of onclick=function(){fn(p)}? The non-parametric function can be written directly as onclick=fn();?
What is the underlying principle? Thanks

高洛峰高洛峰2752 days ago876

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-19 10:33:56

    onclickIn fact, you can directly bind functions with parameters, as follows:

    const input = document.getElementById('input');
    input.onclick = function(params){
      console.log(params);
    };

    However, please note that your requirement is to execute the function fn(p), and the result of the execution is to return a value, not a function.
    fn(p),执行的结果是返回一个值,而不是一个函数。
    onclickAs a callback event when clicked, if bound, it must be bound to a function, not a value. As follows:

    input.onclick = function(){
      fn(p);
    };

    What this means here is to bind an onclick事件,这个事件是一个函数,点击时,回调就被执行了,意味着函数也被执行了,函数执行时,其中的语句fn(p) event to the input. This event is a function. When clicked, the callback is executed, which means that the function is also executed. When the function is executed, the statement fn(p ) is executed.

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:33:56

    onclick = function(e) {console.log(e)}

    Try to bind this click function and see the result

    reply
    0
  • Cancelreply