Duplicate one element's event handlers onto another?

前端 未结 6 1537
半阙折子戏
半阙折子戏 2021-02-14 01:51

How do you copy an event handler from one element to another? For example:

$(\'#firstEl\')
    .click(function() {
        alert(\"Handled!\");
         


        
6条回答
  •  一整个雨季
    2021-02-14 02:19

    This question was already answered but for future reference: you could copy them by iterating the events of the original element and binding their handlers to the target.

    > see edit below!

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

    This is handy when you have no control of the original element (e.g. when using a plugin) and just want to clone the behavior of a certain element.

    Edit: Access to an elements event handlers has been changed in later jQuery versions. This should work for newer versions:

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

    Cheers

提交回复
热议问题