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
PHPz2017-05-19 10:33:56
onclick
In 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)
,执行的结果是返回一个值,而不是一个函数。onclick
As 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.
高洛峰2017-05-19 10:33:56
onclick = function(e) {console.log(e)}
Try to bind this click function and see the result