How to call multiple JavaScript functions in onclick event?

后端 未结 11 1111
梦如初夏
梦如初夏 2020-11-22 06:25

Is there any way to use the onclick html attribute to call more than one JavaScript function?

11条回答
  •  生来不讨喜
    2020-11-22 07:08

    One addition, for maintainable JavaScript is using a named function.

    This is the example of the anonymous function:

    var el = document.getElementById('id');
    
    // example using an anonymous function (not recommended):
    el.addEventListener('click', function() { alert('hello world'); });
    el.addEventListener('click', function() { alert('another event') });
    

    But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.

    Instead, you can use named functions:

    var el = document.getElementById('id');
    
    // create named functions:
    function alertFirst() { alert('hello world'); };
    function alertSecond() { alert('hello world'); };
    
    // assign functions to the event listeners (recommended):
    el.addEventListener('click', alertFirst);
    el.addEventListener('click', alertSecond);
    
    // then you could remove either one of the functions using:
    el.removeEventListener('click', alertFirst);
    

    This also keeps your code a lot easier to read and maintain. Especially if your function is larger.

提交回复
热议问题