4

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

假设我有这个元素:

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

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

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

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

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


我确实看到了这个先前的答案,但有几件事我不明白:

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

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

4

1 回答 1

3

我认为您可以这样做:通过克隆 div 并将数据(“事件”)保存在对象中来存储 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);
     }
   }

 });

在这里小提琴:(与 Katiek 相同)http://jsfiddle.net/nicolapeluchetti/CruMx/2/(如果您不完全单击 div,该事件会触发两次!)我还更新了我的小提琴以使用 jquery 1.5 .2 http://jsfiddle.net/pXAXW/1/ )

于 2011-07-21T21:52:18.793 回答