jQuery绑定事件的四种方式

jQuery中提供了四种事件监听方式,分别是bindlivedelegateon,对应的解除监听的函数分别是unbinddieundelegateoff

bind

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

$(selector).bind(event,data,function)
  • event:事件,必选,一个或多个事件;
  • data:参数,可选;
  • fn:绑定事件发生时执行的函数,必选。
$("#foo").bind('click',function(){
    console.log("clicked");
})

它不会绑定到在它执行完后动态添加的那些元素上。当元素很多时,会出现效率问题。当页面加载完的时候,你才可以进行bind(),所以可能产生效率问题。

live

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

$(selector).live(event,data,function)

delegate

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

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

on

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

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


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

参考文章

jQuery绑定事件的四种方式:bind、live、delegate、on
JQuery中事件绑定的四种方法及其优缺点

你可能感兴趣的:(jQuery绑定事件的四种方式)