How to call multiple JavaScript functions in onclick event?

后端 未结 11 814
梦如初夏
梦如初夏 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:23
    onclick="doSomething();doSomethingElse();"
    

    But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

    0 讨论(0)
  • 2020-11-22 07:26

    This is alternative of brad anser - you can use comma as follows

    onclick="funA(), funB(), ..."
    

    however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).

    function funA() {
      console.log('A');
    }
    
    function funB(clickedElement) {
      console.log('B: ' + clickedElement.innerText);
    }
    
    function funC(cilckEvent) {
      console.log('C: ' +  cilckEvent.timeStamp);
    }
    div {cursor:pointer}
    <div onclick="funA(), funB(this), funC(event)">Click me</div>

    0 讨论(0)
  • 2020-11-22 07:27

    A link with 1 function defined

    <a href="#" onclick="someFunc()">Click me To fire some functions</a>
    

    Firing multiple functions from someFunc()

    function someFunc() {
        showAlert();
        validate();
        anotherFunction();
        YetAnotherFunction();
    }
    
    0 讨论(0)
  • 2020-11-22 07:27

    This is the code required if you're using only JavaScript and not jQuery

    var el = document.getElementById("id");
    el.addEventListener("click", function(){alert("click1 triggered")}, false);
    el.addEventListener("click", function(){alert("click2 triggered")}, false);
    
    0 讨论(0)
  • 2020-11-22 07:27

    You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.

    So the best to do is add them by code as in:

    var element = document.getElementById("multiple_onclicks");
    element.addEventListener("click", function(){console.log("click3 triggered")}, false);
    element.addEventListener("click", function(){console.log("click4 triggered")}, false);
    <button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");'  > Click me</button>

    You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.

    0 讨论(0)
提交回复
热议问题