Using defined function instead of anonymous functi

2019-07-31 04:35发布

Why isn't it possible to use a defined function as event callback?

<div id="me">
  <input>
</div>

$(document).ready(function(){
  // $("#me").on('keyup', 'input', doit()); # doesn't work
  // $("#me").on('keyup', 'input', 'doit'); # neither does this
  $("#me").on('keyup', 'input', function() {
    doit();
  }); // well, this one works of course
});

function doit() {
  console.log($("input").val());
}

4条回答
爷、活的狠高调
2楼-- · 2019-07-31 05:13

You should pass the function, not call it

$("#me").on('keyup', 'input', doit)

To clear why that is wrong, see this example:

$("#me").on('keyup', 'input', (function() {
  doit();
})()); 

Here you are passing an anonymous function and invoking it immediately, which is not what the event handler expects.

The problem is not in the difference between anonymous or not, the problem is that you are invoking the function instead of passing it.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-31 05:14

when you say something=function(){ blah } in js, it stores that as text and parses it on the fly - so yes, you can. For example:

CallMe = function(){ alert("blah!"); }
bobsCallback.setFunction( CallMe );

CallMe is like any other variable, but it's contents is the js for the function. You can pass it around as a callback, or invoke like so:

alert("calling CallMe...");
CallMe();
查看更多
来,给爷笑一个
4楼-- · 2019-07-31 05:17

You need to pass the function in as a parameter.

$("#me").on('keyup', 'input', doit);
查看更多
我想做一个坏孩纸
5楼-- · 2019-07-31 05:19

When you pass in doit() (with the "()") as the callback, you're actually running the function at that point and passing in the return value of the function (likely undefined) as the callback. If you pass in just a reference to the named function doit then the function will be executed as the callback.

查看更多
登录 后发表回答