使用jQuery将事件从一个元素复制到另一个 [英] Copy events from one element to other using jquery
问题描述
我有DOM是这样的:
<a href='javascript:void(0)' id='link1'>Element with events bound initially</a>
<a href='javascript:void(0)' id='link2'>Element to which events are bound in future</a>
还有这个javascript:
And this javascript:
$(function(){
$('#link1').bind('click',function(){alert('do something to make me happy');})
});
现在将来的某个时候,我想将绑定在link1上的所有事件复制到link2上.我正在按照以下说明进行操作,如果可能或可用,请提出一些更好的方法.
Now some time in future i want to copy all events bound on link1 to link2. I am doing it as written below please suggest some better way if possible or available.
var _elmEvents = $(#link1).data('events');
if (_elmEvents) {
$.each(_elmEvents, function (event, handlers) {
$.each(handlers, function (j, handler) {
$('#link2').bind(event, handler);
});
});
}
推荐答案
如果要将所有事件从一个对象复制到另一个对象而不进行克隆,则可以通过直接访问事件数据来实现.
If you want to copy all events from one object to another without cloning, you can do so by accessing the events data directly.
例如,如果您这样做:
$("#the_link").click(function(e){
// do some stuff
return false;
}).mouseover(function(e){
// do some other stuff
});
您可以在元素的事件"数据中访问这些事件关联
You can access those event associates in the 'events' data of the element
var events = $("#the_link").data('events');
它将是一个对象,其键代表事件类型,每个键都包含事件关联数组.无论如何,这是一个简单的示例,不考虑名称空间.
It will be an object whose keys represent the event type, each containing an array of event associations. Regardless, here's a simple example, not accounting for namespaces.
var events = $("#the_link").data('events');
var $other_link = $("#other_link");
if ( events ) {
for ( var eventType in events ) {
for ( var idx in events[eventType] ) {
// this will essentially do $other_link.click( fn ) for each bound event
$other_link[ eventType ]( events[eventType][idx].handler );
}
}
}
这篇关于使用jQuery将事件从一个元素复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!