使用 jquery 将事件从一个元素复制到另一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2337521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:16:43  来源:igfitidea点击:

Copy events from one element to other using jquery

jquery

提问by Praveen Prasad

I have DOM is like this:

我有 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>

And this javascript:

而这个 javascript:

$(function(){
    $('#link1').bind('click',function(){alert('do something to make me happy');})
});

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.

现在,将来某个时候我想将绑定在链接 1 上的所有事件复制到链接 2。我正在按照下面的说明进行操作,如果可能或可用,请提出一些更好的方法。

var _elmEvents = $(#link1).data('events');

if (_elmEvents) {
    $.each(_elmEvents, function (event, handlers) {
        $.each(handlers, function (j, handler) {
            $('#link2').bind(event, handler);
        });
    });
}

采纳答案by BBonifield

If you want to copy all events from one object to another without cloning, you can do so by accessing the events data directly.

如果您想在不克隆的情况下将所有事件从一个对象复制到另一个对象,您可以通过直接访问事件数据来实现。

For instance, if you did:

例如,如果你这样做:

$("#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 );
        }
    }
}

回答by Rikco

This one worked very well in my script.

这个在我的脚本中非常有效。

$.each($('#original').data('events'), function() {
  // iterate registered handler of original
  $.each(this, function() {
    $('#target').bind(this.type, this.handler);
  });
});

I found it here (source): http://snipplr.com/view/64750/

我在这里找到它(来源):http: //snipplr.com/view/64750/

回答by German Latorre

Accepted answer did not work for me as I use namespacesand other events(such as "paste") that are not a method in jQuery.

接受的答案对我不起作用,因为我使用了不是 jQuery 方法的命名空间其他事件(例如“粘贴”)。

This worked for me:

这对我有用:

function copyEvents(source, destination) {
    // Get source events
    var events = source.data('events');

    // Iterate through all event types
    $.each(events, function(eventType, eventArray) {
        // Iterate through every bound handler
        $.each(eventArray, function(index, event) {
            // Take event namespaces into account
            var eventToBind = event.namespace.length > 0
                ? (event.type + '.' + event.namespace)
                : (event.type);

            // Bind event
            destination.bind(eventToBind, event.data, event.handler);
        });
    });
}

回答by noah

You can clonean element and manipulate the new element however you want, however jQuery doesn't provide an easy way to copy event handlers from one element to another. However, the code that would do it would be:

您可以根据需要克隆一个元素并操作新元素,但是 jQuery 没有提供一种简单的方法来将事件处理程序从一个元素复制到另一个元素。但是,可以执行此操作的代码是:

var events = jQuery.data( originalElement, "events" );

for ( var type in events ) {
    for ( var handler in events[ type ] ) {
        jQuery.event.add( targetElement, type, events[ type ][ handler ], events[ type ][ handler ].data );
    }
}

But since it relies somewhat on jQuery internals, I would try to make a solution using clone.

但是由于它在某种程度上依赖于 jQuery 内部结构,因此我会尝试使用 clone 来制作解决方案。

回答by yckart

This is based on Brandonswork, but updated to work with all jQuery-versions. Tested on 1.6.4upto 2.0.x.

这是基于Brandons 的工作,但已更新为适用于所有 jQuery 版本。在1.6.4高达2.0.x.

/**
 * Logic for copying events from one jQuery object to another.
 *
 * @private 
 * @name jQuery.event.copy
 * @param jQuery|String|DOM Element jQuery object to copy events from. Only uses the first matched element.
 * @param jQuery|String|DOM Element jQuery object to copy events to. Copies to all matched elements.
 * @type undefined
 * @cat Plugins/copyEvents
 * @author Brandon Aaron ([email protected] || http://brandonaaron.net)
 * @author Yannick Albert ([email protected] || http://yckart.com)
 */
jQuery.event.copy = function (from, to) {
    from = from.jquery ? from : jQuery(from);
    to = to.jquery ? to : jQuery(to);

    var events = from[0].events || jQuery.data(from[0], "events") || jQuery._data(from[0], "events");
    if (!from.length || !to.length || !events) return;

    return to.each(function () {
        for (var type in events)
        for (var handler in events[type])
        jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
    });
};

回答by xDan

Edited @Rikco answer according to a newer jquery.

根据较新的 jquery 编辑 @Rikco 答案。

function assingEvents() {
     //if you have multiple just use jQuery._data(jQuery('.copy-from-single-item')[0]
     jQuery.each(jQuery._data(jQuery('.copy-from-single-item'), 'events'), function()  {
       // iterate registered handler of original
       jQuery.each(this, function() {
        var parentEvent = this;
        jQuery.each(jQuery('.copy-to-multiple-item'),
            function() {
                jQuery(this).bind(parentEvent.type, parentEvent.handler);
            });
       });
    });
}