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

时间:2012-04-19 05:26:15

标签: 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的新手并且很难过。

4 个答案:

答案 0 :(得分:5)

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

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);
            });
        });
    });
}

答案 1 :(得分:2)

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

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 

     });

    });

});

希望这有帮助。

答案 2 :(得分:2)

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

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

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

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

无论如何它几乎是相同的......

答案 3 :(得分:0)

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