【问题标题】:How can I capture which events were removed with unbind and re-apply them later?如何捕获哪些事件已通过取消绑定删除并稍后重新应用?
【发布时间】:2011-07-21 21:33:43
【问题描述】:

如何存储通过取消绑定删除的事件并在以后重新应用它们?

假设我有这个元素:

<div id="thediv">The Div</div>

它的 onclick 事件附加了不同数量的函数。我知道我可以使用 unbind 来删除所有的 onclick 函数:

$("#thediv").unbind("click");  

如何存储未绑定的函数以便以后重新绑定?

请注意,这必须适用于 jQuery 1.5。


我确实看到了this previous answer ,但有一些我不明白的地方:

  • 为什么是先绑定后解除绑定?
  • ary_handlers[idx] 在做什么?

(我并不是真的在寻找这些问题的答案,除非它们对于解释我关于捕获未绑定函数的问题的解决方案是必要的。)

【问题讨论】:

    标签: jquery jquery-1.5


    【解决方案1】:

    我认为你可以这样做: 您可以通过克隆 div 并将 data('events') 保存在对象中来存储 div 的事件。之后您迭代对象并绑定事件。您必须克隆,因为当您取消绑定事件时,原始数据(“事件”)被删除。(希望我明白您在寻找什么)

    <div id='my'>my</div>
    
    var my = $('#my');
    my.click(function(){
       alert('my');
    });
    
    my.hover(function(){
    $(this).css('color', 'red');
        });
    
    my.click(function(){
       alert('you');
    });
    
    var ev =my.clone(true).data('events');
    
    my.unbind();
    
    for (var e in ev){
        //you have to iterate on the property since is an array with all the handlers for the same event)
        for (i= 0; i < ev[e].length; i++){
           my.bind(e, ev[e][i]);   
        }
    }
    

    小提琴http://jsfiddle.net/pXAXW/

    编辑 - 要在 1.5.2 中进行这项工作,您只需更改附加事件的方式,因为它们的保存方式不同:

      $(document).ready(function(){
    
       var theDiv = $("#thediv");
    
       theDiv.click(function(){
         $(this).css("border-color", "blue");
         alert("Click!");
       });
           theDiv.click(function(){
         $(this).css("border-color", "blue");
         alert("clack!");
       });
    
       var theEvents = theDiv.clone(true).data("events");
    
       //  Unbind events from the target div
       theDiv.unbind("click");
    
       //  Put the saved events back on the target div
       for (var e in theEvents){
         //  must iterate through since it's an array full of event handlers
         for ( i=0; i<theEvents[e].length; i++ ){
           theDiv.bind(e, theEvents[e][i].handler);
         }
       }
    
     });
    

    fiddle here:(与 Katiek 相同)http://jsfiddle.net/nicolapeluchetti/CruMx/2/(如果您没有准确点击 div,则该事件会触发两次!) 我还更新了我的小提琴以使用 jquery 1.5.2 http://jsfiddle.net/pXAXW/1/)

    【讨论】:

    • 这适用于 jQuery 1.6.2 (jsfiddle.net/UZW6T/1),但不幸的是它不适用于 1.5.2 (jsfiddle.net/CruMx/1)。
    • 要使其与 1.5.2 一起使用,它只需要更改绑定事件的方式,因为它们以不同的方式保存:看看我的答案
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2023-03-18
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2013-03-31
    相关资源
    最近更新 更多