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/