on(),bind(),live()用法的區別
以上三種函數都可以為一個頁面元素綁定事件,其中on()是核心,其他兩個用法上略有不同。
下面貼上bind(),live()的代碼
jQuery.fn.extend({
...
bind: function( types, data, fn ) {
return this.on( types, null, data, fn ); //第二個參數為null
},
...
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
//第二個參數為選擇器所選中的jq元素
return this;
},
...
});
可以看出,bind(),live()都是調用的on()函數,只不過是傳遞的參數不同。
體現在用法上的區別如下:
$('#id').bind('click',function(){});
$('#id').bind('click','div',function(){});
//以上兩種方法都把事件綁定到$('#id')上,因為bind()方法把‘div’設為null
$('#id').live('click',function(){});
$('#id').live('click','div',function(){});
//第二種方法可以將事件綁定到$('#id div')中
on()函數代碼解析
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
....//判斷參數類型,確定相應參數
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
}
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
....
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
....
}
....
}
原理從代碼中可以看出,其實還是調用原生JavaScript中的綁定事件接口。值得一提的是,在為頁面中的元素組進行綁定事件的時候,要考慮使用事件代理的方法對代碼進行優化。例子如下:
$('#myTable td').on('click',function(){
$(this).css('background','red');
});
//給每一個td元素都綁定事件
$('#myTable').on('click',function(e){
var $clicked = $(e.target); //e.target可以捕捉到觸發事件的目標
$clicked.css('background','red');
});
//這種使用事件代理的方法只需向父元素綁定一個事件
$('#myTable td').on('click','td',function(){
$(this).css('background','red');
});
//jquery中的on()方法將這種事件監聽封裝起來。
關於事件對象event的事件目標屬性,在dom中這個屬性名是
target,在IE對象中這個屬性名是srcElement.
