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

假设我有这个元素:

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

它的 onclick 事件附加了不同数量的函数。我知道我可以使用 unbind 删除所有 onclick 功能:
$("#thediv").unbind("click");

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

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

我确实看到了 this previous answer ,但有几件事我不明白:
  • 为什么是先绑定(bind)后解除绑定(bind)?
  • ary_handlers[idx] 在做什么?

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

    最佳答案

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

    <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]);
        }
    }
    

    fiddle 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 :(与 Katiek 相同)http://jsfiddle.net/nicolapeluchetti/CruMx/2/(如果您没有完全点击 div,则事件会触发两次!)
    我还更新了我的 fiddle 以使用 jquery 1.5.2 http://jsfiddle.net/pXAXW/1/ )

    关于jquery - 如何捕获哪些事件被取消绑定(bind)删除并在以后重新应用它们?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6783089/

    10-12 01:09
    查看更多