其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

jquery的on方法源码

GG网络技术分享 2025-03-18 16:17 0


jquery的on方法是一个非常重要的事件绑定方法,可以简化事件处理程序的编写,并可以动态添加元素的事件绑定。下面是on方法的源码分析:

jQuery.fn.on = function( 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 ) {

this.on( type, selector, data, types[ type ], one );

}

return this;

}

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 this;

}

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 this.each( function() {

jQuery.event.add( this, types, fn, data, selector );

} );

};

首先,on方法接收四个参数:types、selector、data、fn,其中types是绑定的事件类型,可以是单个事件类型,也可以是一个对象,selector是选择器字符串,用于过滤子元素,data是传递给事件处理程序的附加数据,fn是事件处理程序的函数,可以是一个函数,也可以是false,如果是false,则是返回false的函数。

代码中,通过对四个参数进行处理,确定类型type、选择器selector和数据data,最终将事件处理程序fn添加到事件队列中,实现事件绑定。此外,还支持通过one变量来实现只绑定一次事件的绑定方式。

总之,on方法是一个非常重要的事件绑定方法,它方便了开发者的事件处理程序编写,并能够实现动态添加元素的事件绑定。

标签: 绑定 事件

提交需求或反馈

Demand feedback