使用jQuery将事件处理程序从一组元素复制到另一组元素

我有以下内容

var $header = $('.inner th'); var $fixedHeader = $(".header1 th"); $header.each(function (index) { // i need to copy all events from $header[index] to $fixedHeader[index] }); 

如何将事件处理程序(onClick,onDblClick..etc)从第一组中的元素复制到第二组中的相邻元素? 我是jquery的新手并且很难过。

您需要使用jquery的.data(’events’)方法。

我提供了一个有效的jsFiddle来了解从哪里开始。

http://jsfiddle.net/hx8gf/2/

我知道Alphamale打败了我,但我仍然会发布它,因为它很有帮助。

无论如何它几乎相同……

我知道这已经回答了几次,但这是一个全面的解决方案,基于以前的解决方案。

 function copyEvents(source, destination) { var events; //copying from one to one or more source = $(source).first(); destination = $(destination); //get all the events from the source events = $(source).data('events'); if (!events) return; //make copies of all events for each destination destination.each(function() { var t = $(this); $.each(events, function(index, event) { $.each(event, function(i, v) { t.bind(v.type, v.handler); }); }); }); } 

这样的事情可能会有所帮助:

 var header = $('.inner th'); var fixedHeader = $(".header1 th"); header.each(function (index) { var events = $(header).data("events"); //Gives you all events of an element $.each(events, function(i, event) { //Loop through all the events $.each(event, function(j, h) { //Loop through all the handlers attached for a event fixedHeader.bind(i, h.handler); //Bind the handler with the event }); }); }); 

希望这可以帮助。

jquery中的clone(true)函数不能复制事件处理,但它只能复制元素。如果要复制它,它将要添加事件绑定。 您可以查看JQUERY的事件绑定。 在回调函数中调用绑定函数。 这可能有所帮助。