开发者

What is difference between $(".anything").click() and $(".anything").bind(click)

What is difference between $(".anything").click() and $(".anything").bind(click)

$(".anything").click(function() {

});

$(".any开发者_开发技巧thing").bind('click', function() {

});


Nothing, click(function() { }) is just a shortcut for bind("click", function() { }).

From the jQuery docs:

The jQuery library provides shortcut methods for binding the standard event types, such as .click() for .bind('click').

You can read more about bind() here.


The first is a shortcut of the second. The second is actually wrong, click should have been quoted. Further, in the second you have the added benefit that you can bind the same function to multiple events, each separated by a space. E.g.

$(".anything").bind("click keypress blur", function() {

});


In that specific case, absolutely nothing.

However:

A) If you give .click() no argument, it triggers the event instead of setting the handler.

B) only .bind() lets you use the "namespaced" way of registering handlers:

$(whatever).bind('click.myEvent', function (e) { ... });
$(whatever).unbind('click.myEvent'); // Removes just that handler


See this post, which points to the JQuery source to show that .click(fn) just calls .bind('click', fn): jQuery: $().click(fn) vs. $().bind('click',fn);

I usually only use the latter if:

  • I want to bind multiple things, i.e. .bind('click focus', fn)
  • Just to maintain convention if I call unbind later, i.e.:
var fn = function() { alert('foo'); }
$('#foo').bind('click', fn);

...

$('#foo').unbind('click', fn);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜