gpt4 book ai didi

javascript - 在 jQuery 1.8.3 中,将存储的事件添加回元素

转载 作者:行者123 更新时间:2023-11-30 16:52:58 25 4
gpt4 key购买 nike

在 jQuery 1.8.3 中,我可以使用 var events = $._data($('#button')[0], 'events');

如果我取消绑定(bind)这些事件,以后如何将它们添加回元素?

$('#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>

最佳答案

我不会在任何地方推荐它,但如果你想这样做(或者只是想知道为什么它不起作用)

$('#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>

关于javascript - 在 jQuery 1.8.3 中,将存储的事件添加回元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30212705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com