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

标签 javascript jquery event-handling

jQuery 中下面两个语句有什么不同:

1) 使用 .bind

$("#username").bind('click',function(){
    //@todo
});

2) 没有 .bind()

$("#username").click(function(){
    //@todo
});    

那么,什么时候我需要使用其中之一呢?

最佳答案

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

This method is a shortcut for .bind('click', handler)

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

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

我倾向于使用 .click 而不是 .bind,因为这样写起来更快。但是,.bind 可用于将同一个监听器附加到多个事件,因此在这种情况下它很有用:

$("#something").bind("click mouseover", function() {
    //Do stuff
});

为了扩展@Tomalak 的评论,.bind 在处理自定义事件时也很有用。对于几乎所有其他事件,都有一个 shortcut method就像 .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*/
});

关于javascript - jQuery 中的 .bind ('click' ) 和 .click() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7474199/

相关文章:

javascript - 将函数 Hook 到原型(prototype)或不 Hook 之间的区别

javascript - 使用jquery将结果加载到页面中

json - 为什么 getjson 仅返回 1 行

jquery - 使用 Jquery 返回 CSS 高度,未计算,但已声明

javascript - 我可以如何操作用户编辑输入字段后显示的字符

javascript - jquery setInterval 与 fadeOut/In

javascript - x 不是函数...您希望 Object.create 对构造函数做什么

javascript - Lodash _.hasIntersection?

event-handling - 如何绑定(bind)到 jQuery UI 选项卡事件单击/选择/事件?

macos - 将完成处理程序添加到 presentViewControllerAsSheet(NSViewController)?