jQuery中.bind('click')和.click()有什么区别?

vie*_*ean 11 javascript jquery event-handling

jQuery中以下两个语句之间有什么不同:

1)用 .bind

$("#username").bind('click',function(){
    //@todo
});
Run Code Online (Sandbox Code Playgroud)

2)没有 .bind()

$("#username").click(function(){
    //@todo
});    
Run Code Online (Sandbox Code Playgroud)

那么,当我需要使用其中一个?

Jam*_*ice 23

没有区别.如果您阅读了文档,.click则会注意到以下行:

这个方法是.bind('click',handler)的快捷方式

您可以通过快速查看jQuery源来确认这一点:

function (data, fn) {
    if (fn == null) {
        fn = data;
        data = null;
    }
    //Notice the call to bind on the following line...
    return arguments.length > 0 ? this.bind(name, data, fn) : this.trigger(name);
}
Run Code Online (Sandbox Code Playgroud)

我倾向于使用.click.bind,只是因为它是更快地写.但是,.bind可以用于将同一个侦听器附加到多个事件,因此在这种情况下它很有用:

$("#something").bind("click mouseover", function() {
    //Do stuff
});
Run Code Online (Sandbox Code Playgroud)

要扩展@Tomalak的注释,.bind在使用自定义事件时也很有用.对于几乎任何其他事件,有一个快捷方法就像.click.jQuery源代码如下:

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
    /*Call .bind for the respective event. There is a shortcut method 
    for each of the events listed above*/
});
Run Code Online (Sandbox Code Playgroud)