Home >Daily Programming >HTML Knowledge >How to call multiple js functions in click event
To realize the function of calling multiple functions for the click event in js, we can use the addEventListener() method. That is to say, if you want to call or execute multiple functions in the button's click event, you can use the JavaScript addEventListener() method.
Below we will combine specific code examples to introduce to you the implementation method of calling multiple functions by the click event in js.
The code example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>click事件中调用多个js函数的方法示例</title> </head> <body> <button type="button" id="myBtn">点我</button> <script> // 定义自定义函数 function sayHello(){ alert("Hello World! sayHello() 函数执行成功!"); } function sayHi(){ alert("Hi There! sayHi() 函数执行成功!"); } // 选择按钮元素 var btn = document.getElementById("myBtn"); // 将事件侦听器分配给按钮 btn.addEventListener("click", sayHello); btn.addEventListener("click", sayHi); </script> </body> </html>
In the above code, two functions sayHello() and sayHi() are customized. Then get the button element through the getElementById method. Then use the addEventListener method to assign the same event to the button button, which is the click click event, and call two different custom functions.
The effect is shown in the figure below:
Note: The addEventListener() method is used to add an event handler to the specified element.
The syntax:
element.addEventListener(event, function, useCapture)
The parameters respectively represent:
event (must) represents a string and specifies the event name.
function (required) indicates the function to be executed when the event is triggered.
When the event object is passed into the function as the first parameter. The type of event object depends on the specific event.
useCapture (optional). A Boolean value indicating whether the specified event is executed in the capture or bubbling phase.
This article is about the implementation method of calling multiple js functions for click events. It is also very simple. I hope it will be helpful to friends in need!
The above is the detailed content of How to call multiple js functions in click event. For more information, please follow other related articles on the PHP Chinese website!