您的位置:首页 > Web前端 > JQuery

jQuery中的bind(), live(), on(), delegate()

2012-10-09 17:42 337 查看
当我们试图绑定一些事件到DOM元素上的时候,我相信上面这4个方法是最常用的。而它们之间到底有什么不同呢?在什么场合下用什么方法是最有效的呢?

准备知识:

当我们在开始的时候,有些知识是必须具备的:

DOM树

下图仅仅是一个示例,这是一个在browser环境下的一棵模拟DOM树,在下面的代码中仅起到演示的作用:

View Code

bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},

live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},

delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},


看一下,我们用如何用.on()来改写前面通过 .bind(), .live(), .delegate()所注册的事件:

/* The jQuery .bind(), .live(), and .delegate() methods are just one
line pass throughs to the new jQuery 1.8.2 .on() method */

// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );

// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );

// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );


优点:

提供了一种统一绑定事件的方法

仍然提供了.delegate()的优点,当然如果需要你也可以直接用.bind()

缺点:

也许会对你产生一些困扰,因为它隐藏了一前面我们所介绍的三种方法的细节。

结论:

用.bind()的代价是非常大的,它会把相同的一个事件处理程序hook到所有匹配的DOM元素上

不要再用.live()了,它已经不再被推荐了,而且还有许多问题

.delegate()会提供很好的方法来提高效率,同时我们可以添加一事件处理方法到动态添加的元素上。

我们可以用.on()来代替上述的3种方法

参考资料:

http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: