Duplicate one element's event handlers onto another?

前端 未结 6 1670
半阙折子戏
半阙折子戏 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:31

    You can't easily (and probably shouldn't) "copy" the event. What you can do is use the same function to handle each:

    var clickHandler = function() { alert('click'); };
    // or just function clickHandler() { alert('click'); };
    
    $('#firstEl').click(clickHandler);
    
    // and later
    $('#secondEl').click(clickHandler);
    

    Alternatively you could actually fire the event for the first element in the second handler:

    $('#firstEl').click(function() {
        alert('click');
    });
    
    $('secondEl').click(function() {
        $('#firstEl').click();
    });
    

    Edit: @nickf is worried about polluting the global namespace, but this can almost always be avoided by wrapping code in an object:

    function SomeObject() {
        this.clickHandler = function() { alert('click'); };
    }
    SomeObject.prototype.initFirstEvent = function() {
        $('#firstEl').click(this.clickHandler);
    };
    SomeObject.prototype.initSecondEvent = function() {
        $('#secondEl').click(this.clickHandler);
    };
    

    or wrapping your code in an anonymous function and calling it immediately:

    (function() {
        var clickHandler = function() { alert('click'); };
        $('#firstEl').click(clickHandler);
        $('#secondEl').click(clickHandler);
    })();
    

提交回复
热议问题