请提前阅读:点击打开链接
unbind方法源码:
unbind: function( types, fn ) {
return this.off( types, null, fn );
}
undelegate方法源码:
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
off用法1:
var func=function(){alert("invoke2")};
var func1=function(){alert("invoke2")};
$("#input").on("click",func);
$("#input").on("mouseover",func1);
$("#input").off({"click":func,"mouseover":func1});
off用法2:
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
用法实例:
var func=function(){alert("invoke2")};
var func1=function(){alert("invoke2")};
$("#input").on("click",func);
$("#input").on("mouseover",func1);
//这里虽然传入的false并且变化为returnFalse,但是因为没有returnFalse的
//绑定,在remove函数中什么也不做!mouseover事件和click事件仍然存在!
$("#input").off("mouseover",false);
note:这种情况调用的方式就是off("click",false)那么把fn设置为false,然后接下来把fn设置为returnFalse函数!因为没有为对象绑定returnFalse函数,所以在remove函数中什么也不做!
off方法源码:
//调用方式:jQuery().off( event );
//详见该链接:注意事项:(1)off的选择器必须和on的选择器是一样的
//调用方式:$body.off("click", ":button", btnClick2);
off: function( types, selector, fn ) {
var handleObj, type;
//如果types存在,同时types有preventDefault和handleObj对象
//很显然这样的off方法是用于内部调用的!
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
//如果是对象,那么也就是按照像on方法一样添加$("body").on(events, "#n5", data);
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
//那么对每一个调用对象单独移除事件!
this.off( type, selector, types[ type ] );
}
return this;
}
//如果selector是false或者是函数,那么调用就是off(types,fn)
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
//如果函数是fn===false那么移除的函数就是returnFalse函数!
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
//调用对象的DOM元素,types是字符串,fn是回调函数,selector是选择器
jQuery.event.remove( this, types, fn, selector );
});
}
从源码可以看出:
(1)unbind和undelegate方法都是通过调用调用对象的off方法来解除事件绑定的!但是unbind的selector是null表明这个事件是直接绑定在调用对象上面的,不是进行了代理的
(2)bind方法不适用于后面动态添加的对象,但是delegate适用于后面动态添加的对象,也就是动态添加的对象也会有相应的对象,因为他是通过代理来完成的!而不是直接绑定!
(3)如果undelegate只是传入的一个参数,那么调用this.off( selector, "**" ) :否则调用this.off( types, selector || "**", fn );但是底层都是调用jQuery.event.remove方法