将一个元素的事件处理程序复制到另一个元素上 [英] Duplicate one element's event handlers onto another?
问题描述
如何将事件处理程序从一个元素复制到另一个元素?例如:
$('#firstEl')
.click(function() {
alert("Handled!");
})
;
// here's where the magic happens
$('#secondEl').click = $('#firstEl').click; // ????
请注意,第二个元素正在不同的时间处理,当第一个元素获取其处理程序时,这意味着:
Note that the second element is being processed at a different time to when the first element is getting its handler, meaning that this:
$('#firstEl, #secondEl').click(function() { ... });
...将无法正常工作。
...won't work.
推荐答案
这个问题已经回答了,但为了将来可以参考:你可以通过迭代原始元素的事件并将其处理程序绑定到目标来复制它们。
This question was already answered but for future reference: you could copy them by iterating the events of the original element and binding their handlers to the target.
请参阅下面的编辑
// iterate event types of original
$.each($('#original').data('events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
当您无法控制原始元素(例如使用插件)时,这很方便,只是想要克隆某个元素的行为。
This is handy when you have no control of the original element (e.g. when using a plugin) and just want to clone the behavior of a certain element.
编辑:访问元素事件处理程序已在以后的jQuery版本中更改。这应该适用于较新版本:
Access to an elements event handlers has been changed in later jQuery versions. This should work for newer versions:
$.each($._data($('#original').get(0), 'events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
干杯
这篇关于将一个元素的事件处理程序复制到另一个元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!