javascript - Why can't onclick directly call a parameter-containing function but needs to be written in the form onclick=function(){fn(p)}?
高洛峰
高洛峰 2017-05-19 10:31:56
0
2
862

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
PHPzhong

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.

小葫芦
onclick = function(e) {console.log(e)}

Try to bind this click function and see the result

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template