JQuery中事件绑定的四种方法及其优缺点

JQuery中事件绑定的方法有bindlivedelegateon

1、bindbind(type [,data], fn)

.bind监听器绑定到目标元素上,会将所有匹配的元素都绑定一次事件。因此,当元素很多时,后来动态添加的元素不会被绑定。
例:

$("#foo").bind('click',function(){
    console.log("clicked");
})

简写:

$("#foo").click(function(){
    console.log("clicked");
})

2、live

.live,监听器绑定到document上,利用事件委托,可以像调用bind一样调用live方法,但两者的底层实现不一样。.live绑定的事件也会匹配到那些动态添加的元素,而且,被live绑定的事件只会被附加到document元素上一次,因此提高了性能。
例:

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

注意:该方法在1.7版本后被弃用

3、delegate$(selector).delegate(childSelector,event,data,function)

.delegate与.live类似,不会监听器绑定到你指定的附加元素上,而不是document
上,也利用了事件委托,因此也提高了性能。但是该方法不能直接由bind过渡
例:

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

4、on$(selector).on(event,childSelector,data,function)

1.7版本新添加的,也是推荐使用的事件绑定方法。其实bind、live、delegate都是通过该方法实现的:

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 ) {
 return arguments.length == 1 ? 
  this.off( selector, "**" ) : 
  this.off( types, selector, fn );

因此,使用on方法和使用以上个方法的一样

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

对于只需要触发一次,随后就要立即解除绑定的情况,也可以使用one()方法。即在每个对象上,事件处理函数只会被执行一次。

猜你喜欢

转载自blog.csdn.net/liwenfei123/article/details/80408537