jQuery different events on different elements to trigger the same function

前端 未结 3 617
旧巷少年郎
旧巷少年郎 2021-01-21 17:40

What if different elements have to trigger the same function but on different events ?

$(\'#btnNext\').on(\'click\', function() { /*Same thing*/ });

$(\'#txtFie         


        
相关标签:
3条回答
  • 2021-01-21 17:52

    You included a clue in your question: "trigger the same function" - so simply bind the same function:

    function commonHandler(e) { /* your code */ }
    
    $('#btnNext').on('click', commonHandler);
    
    $('#txtField').on('change blur', commonHandler);
    
    0 讨论(0)
  • 2021-01-21 18:02
    $('#btnNext').on('click', myMethod );
    
    $('#txtField').on('change blur',  myMethod );
    
    function myMethod()
    {
    /*Your Code goes here*/
    }
    
    0 讨论(0)
  • 2021-01-21 18:08

    Here is a jsFiddle For You

    Fiddle Here

     function Commonalert(){alert("Common Alert Message");}
    
    $('#Btn').on('click', Commonalert);
    
    $('#text').on('change blur', Commonalert);
    
    0 讨论(0)
提交回复
热议问题