首页 > on(), live(), bind() 之间有什么区别呢

on(), live(), bind() 之间有什么区别呢

jQuery中看着实现的效果都是一样的,不知道有什么具体区别呢?


http://api.jquery.com/live/
Attach an event handler for all elements which match the current selector, now and in the future. (动态生成的也行)

--------------------------------------
http://api.jquery.com/bind/
Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. (先决条件,绑定的dom element必须已经存在)
------------------

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

手册上有相关用法例子

$("a.offsite").live("click", function(){ alert("Goodbye!"); });               
$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });
$('#foo').bind('click', function() {alert('User clicked on "foo."');});

on的这个$(document), 请参考 http://stackoverflow.com/questions/81...


bind是直接绑定在一个对象上。

$('#foo').bind('click', function() {
    alert('User clicked on "foo."');
});

这个例子的是绑定在 #foo 这个元素上。点击#foo元素后执行回调函数。

on方法是一个事件委托。

$('#foo').on("click", "a", function(){ 
    alert("Goodbye!");
});

这个例子是委托在 #foo 这个元素上,点击 #foo 的子元素 a 标签才执行回调函数。

live 方法是on方法的一种实现。

$('a').live('click', function(){ 
    alert("Goodbye!");
});
$(document).on("click", "a", function(){ 
    alert("Goodbye!");
});

上面这两个方法完全相同,后者是前者的具体实现。


不要管他们的区别。用1.9版本JQ,只有on

【热门文章】
【热门文章】