我有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>
Run Code Online (Sandbox Code Playgroud)
这个javascript:
$(function(){
$('#link1').bind('click',function(){alert('do something to make me happy');})
});
Run Code Online (Sandbox Code Playgroud)
现在将来有一段时间我想将link1上绑定的所有事件复制到link2.我这样做如下所示,如果可能或可用,请建议一些更好的方法.
var _elmEvents = $(#link1).data('events');
if (_elmEvents) {
$.each(_elmEvents, function (event, handlers) {
$.each(handlers, function (j, handler) {
$('#link2').bind(event, handler);
});
});
}
Run Code Online (Sandbox Code Playgroud)
BBo*_*eld 15
如果要将所有事件从一个对象复制到另一个对象而不进行克隆,则可以通过直接访问事件数据来实现.
例如,如果您这样做:
$("#the_link").click(function(e){
// do some stuff
return false;
}.mouseover(function(e){
// do some other stuff
});
Run Code Online (Sandbox Code Playgroud)
您可以在元素的"事件"数据中访问这些事件关联
var events = $("#the_link").data('events');
Run Code Online (Sandbox Code Playgroud)
它将是一个对象,其键表示事件类型,每个事件包含一组事件关联.无论如何,这是一个简单的例子,不考虑命名空间.
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 );
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个脚本在我的脚本中效果很好。
$.each($('#original').data('events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
Run Code Online (Sandbox Code Playgroud)
我在这里找到它(源):http : //snipplr.com/view/64750/