jQuery是一個JavaScript庫,為用戶提供了一組先進的工具和技術來處理HTML文檔、處理事件、創(chuàng)建動畫效果以及與服務器通信等。其中,jquery on()方法可以用來將事件處理程序綁定到元素。下面是jquery on()的源代碼:
jQuery.fn.on = function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
};
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
在這段代碼中,我們可以看到on()方法接受四個參數(shù):types、selector、data 和 fn。如果參數(shù)types是一個對象,那么將會遍歷對象中的屬性,分別調用on()方法處理每個屬性。如果參數(shù)types不是對象,那么就需要進一步處理后面的參數(shù)。如果沒有傳入data和fn參數(shù),那么就將selector和fn參數(shù)進行交換,如果只傳入了selector參數(shù),那么fn默認為data。如果fn是false,那么就將其替換為returnFalse()函數(shù)。如果沒有傳入fn參數(shù),那么就返回elem元素。如果傳入了參數(shù)one并且值為1,那么將會添加一個新的事件處理函數(shù),并在事件觸發(fā)時立即移除。最終,每個元素都將循環(huán)遍歷并調用jQuery.event.add()方法,將具體的事件處理綁定到元素上。