分离并重新附加事件监听器

时间:2015-06-17 06:20:38

标签: jquery event-listener

假设我不知道首先附加的函数,有没有办法分离和重新附加事件监听器?

//Unknown click function
$(target).click(function(e){
    //some function
});

//code to detach click function
$(target).mousedown(function(e){
    if(/*something*/){
        //The next line does not work. What could be done instead?
        this.clickFunction = $(target).click;
        $(target).off("click");
    }
});

//code to reattach click function
$(target).mouseup(function(e){
    if(this.clickFunction){
        $(target).click(this.clickFunction);
        this.clickFunction = null;
    }
});

2 个答案:

答案 0 :(得分:1)

jQuery在内部将事件函数保存为:

$._data(target, "events")

其中“target”是DOM元素而不是jQuery对象。

https://stackoverflow.com/a/2518441/806777

所以示例代码是:

//Unknown click function
$(target).click(function (e) {
    //some function
});

//code to detach click function
$(target).mousedown(function (e) {
    if (/*something*/) {
        this.clickFunctions = [];
        var click = $._data(target, "events").click;
        for(var i = 0; i < click.length; i++) {
            this.clickFunctions.push(click[i].handler);
        }
        $(target).off("click");
    }
});

//code to reattach click function
$(target).mouseup(function (e) {
    if (this.clickFunctions) {
        for (var i = 0; i < this.clickFunctions.length; i++) {
            $(target).click(this.clickFunctions[i]);
        }
        this.clickFunctions = null;
    }
});

https://jsfiddle.net/UziTech/176fzorn/

答案 1 :(得分:0)

使用如下所示的jquery unbind()来分离,

$(target).unbind('click');
$(target).unbind('mousedown');
$(target).unbind('mouseup');

您可以使用bind()

重新加载
$(target).bind('click',function(){
  //some code
});
 $(target).bind('mousedown',function(){
//some code
});
 $(target).bind('mouseup',function(){
 //some code
});