Combine multiple click handlers into one

后端 未结 2 1064
自闭症患者
自闭症患者 2021-01-26 17:44

Say I have two click handlers which perform the same functionality :

$(\'#div1\').click(function(event) {  
alert(\'here\');                              
});

$         


        
相关标签:
2条回答
  • 2021-01-26 18:22

    Try this:

    $('#div1, #div2').click(function(event) {  
       alert('here');                              
    });
    

    Furthermore, if you have a lot of div elements, contained in a common parent, you may take benefit of event delegation and attach a single handler to the parent itself, like so:

    $('.common-parent').on('click', 'div', function(event) {  
       ...                          
    });
    
    0 讨论(0)
  • 2021-01-26 18:23

    First way :

    $('#div1, #div2').click(function(event) {  
         alert('here');                              
    });
    

    Second way :

    function doIt(e) {
        alert('here');
    }
    $('#div1').click(doIt);
    $('#div2').click(doIt);
    

    Note that the fact you have this problem sometimes means you should use a class and not just id, so that you may do something like

    $('.alertable').click(function(event) {  
         alert('here');                              
    });
    
    0 讨论(0)
提交回复
热议问题