JQuery中事件綁定的方法有bind
、live
、delegate
、on
1、bind
:bind(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()
方法。即在每個對象上,事件處理函數只會被執行一次。