jQuery:使用预定义函数添加更改事件处理程序 [英] jQuery: adding change event handler with predefined function

查看:122
本文介绍了jQuery:使用预定义函数添加更改事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下内容:

var change_handler = function(element) {
    // ... do some fancy stuff ...
}

现在,我想把它附加到一个元件。哪个是更好/最好或更正确的方法?

Now, I want to attach this to an element. Which is the better/best or more correct method?

$('element_selector').change(change_handler(this));

或...

$('element_selector').change(function() { change_handler(this); });

如果您将对象传递给函数,它会有什么不同吗?

And does it make any difference if you're passing the object to the function or not?

推荐答案

两者都不..

$('element_selector').change(change_handler);

change_handler 将是指尖方法和元素的参数已经由jQuery传递

change_handler will be the so to speak pointer to the method and the argument of the element is already passed by jQuery

如果你要使用 $('element_selector')。change(change_handler) (this)); 它实际上不会将方法指定为处理程序,而是运行方法并尝试将结果指定为处理程序,另一个选项是多余的,因为您可以使用方法名称如上所述,而不是重新包装方法。

If you were to use $('element_selector').change(change_handler(this)); it wouldn't actually assign the method as the handler but rather run the method and attempt to assign the result as the handler, the other option is superfluous because you can use the method name as described above instead of re-wrapping the method.

这篇关于jQuery:使用预定义函数添加更改事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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