简体   繁体   English

jQuery:$()。click(fn)vs. $()。bind('click',fn);

[英]jQuery: $().click(fn) vs. $().bind('click',fn);

When using jQuery to hookup an event handler, is there any difference between using the click method 当使用jQuery连接事件处理程序时,使用click方法之间是否有任何区别

$().click(fn)

versus using the bind method 与使用绑定方法

$().bind('click',fn);

Other than bind's optional data parameter. 除了bind的可选数据参数。

For what it's worth, from the jQuery source : jQuery源代码来看它的价值:

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
    "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
    "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

    // Handle event binding
    jQuery.fn[name] = function(fn){
        return fn ? this.bind(name, fn) : this.trigger(name);
    };
});

So no, there's no difference - 所以不,没有区别 -

$().click(fn)

calls 电话

$().bind('click',fn)

+1 for Matthew's answer, but I thought I should mention that you can also bind more than one event handler in one go using bind 为Matthew的答案+1,但我想我应该提一下,你也可以使用bind一次绑定多个事件处理程序

$('#myDiv').bind('mouseover focus', function() {
    $(this).addClass('focus')
});

which is the much cleaner equivalent to: 这是更清洁相当于:

var myFunc = function() {
    $(this).addClass('focus');
};
$('#myDiv')
    .mouseover(myFunc)
    .focus(myFunc)
;

There is one difference in that you can bind custom events using the second form that you have. 有一个区别在于您可以使用您拥有的第二个表单绑定自定义事件。 Otherwise, they seem to be synonymous. 否则,它们似乎是同义词。 See: jQuery Event Docs 请参阅: jQuery Event Docs

I find the .click() is way more logical, but I guess it's how you think of things. 我发现.click()更合乎逻辑,但我想你是怎么想的。

$('#my_button').click(function() { alert('BOOM!'); });

Seems to be about as dead simple as you get. 似乎就像你得到的一样简单。

There is the [data] parameter of bind which will occur only at bind-time, once. bind的[data]参数只在绑定时发生一次。

You can also specify custom events as the first parameter of bind. 您还可以将自定义事件指定为bind的第一个参数。

If you have Google Chrome, their developer tools have an event listener tool, select the element you want to spy its' event. 如果您使用谷歌浏览器,他们的开发人员工具有一个事件监听工具,请选择您要监视其活动的元素。

You'll find that trying the both ways lead to the same result, so they are equivalent. 您会发现尝试两种方式会产生相同的结果,因此它们是等效的。

I prefer .bind() because of its interface consistency with .live() . 我更喜欢.bind(),因为它与.live()的接口一致。 Not only does it make the code more readable, but it makes it easier to change a line of code to use one method instead of the other. 它不仅使代码更具可读性,而且更容易更改一行代码而不是另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM