2015-05-13 21 views
1

在jQuery的1.8.3,我可以得到的事件绑定到一个元素与var events = $._data($('#button')[0], 'events');在jQuery的1.8.3,增加存储的事件回到单元

如果我取消绑定这些事件,我怎样才能将它们添加回元素后来?

$('#button').click(function() { 
 
    console.log('click triggered'); 
 
}); 
 
var events = $._data($('#button')[0], 'events'); // gets current events 
 
$('#button').unbind(); 
 
$._data($('#button')[0], 'events', events); // doesnt work 
 
$('#button').data('events', events); // doesnt work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<button type="button" id="button">Change condition</button>

+0

你为什么想这么做...... –

+0

@ArunPJohny想象我正在向存在的某些功能添加功能ing页面。我可以添加代码,但我不允许编辑已存在的代码。现有的代码将事件处理程序添加到页面上的所有单选按钮(包括我将添加的一些单选按钮)。我想从我添加的元素中解除这些处理程序的绑定,但我可能需要稍后恢复这些更改。 – DelightedD0D

回答

2

我不会推荐它的任何地方,但还是如果你想要做的(或只是知道为什么它不工作)

$('#button').click(function() { 
 
    console.log('click triggered'); 
 
}); 
 
//this returns the events object, but the problem is when an handler is removed it is removed from this object so just keeping this reference is useless 
 
var events = $._data($('#button')[0], 'events'); 
 

 
//here we create a deep copy of the events, so _e will be freezed even though events is modifed 
 
var _e = $.extend(true, {}, events); 
 

 
$('#button').unbind(); 
 

 
//the events object is empty here but _e is not 
 
console.log('events', events); 
 
console.log('_e', _e); 
 

 
//now just adding the _e data won't be enough as it requires some native handlers to be added. 
 
$.each(_e, function(key) { 
 
    //so we iterate over each available event type and add a noop function as the handler 
 
    $('#button').on(key, $.noop); 
 
    //calling the previous line will create a new events.<event-name> object 
 
    var events = $._data($('#button')[0], 'events'); 
 
    //now override the events definition with the copy we have 
 
    events[key] = _e[key]; 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<button type="button" id="button">Change condition</button>

+0

https://jsfiddle.net/arunpjohny/y4z63j8o/2/ –