使用定义的函数代替匿名函数作为回调 [英] Using defined function instead of anonymous function as callback

查看:84
本文介绍了使用定义的函数代替匿名函数作为回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能使用已定义的函数作为事件回调?

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());
}

推荐答案

您应该传递函数,而不要调用它

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.

这篇关于使用定义的函数代替匿名函数作为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆