Home > Article > Web Front-end > There are several ways to add events to elements in javascript
Javascript has three ways to add events to elements, namely: 1. Binding directly in the html tag; 2. Binding after obtaining the corresponding dom element in js; 3. Using addEventListener in js to implement binding Certainly.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Bind directly in the html tag;
2. Obtain the corresponding dom element in js and bind it;
3. Use addEventListener in js () to implement binding;
The specific code examples are as follows:
<!-- 以下为给dom元素绑定js事件的三种方法 --> <!-- 1--html内直接绑定 --> <input type="button" id="btn0" onclick="alert('执行了html绑定的方法')" value="html中绑定"></input> <!-- 2--使用js绑定 --> <input type="button" id="btn1" value="js绑定"> <!-- 3--使用addEventListener绑定 --> <input type="button" id="btn2" value="addEventListener绑定"></input> <script> //********js绑定事件的js代码********* let button1 = document.getElementById("btn1") button1.onclick = function() { console.log("执行了js绑定的事件") } //将覆盖之前绑定的onclick事件 button1.onclick = function() { console.log("执行了js绑定的第二个事件") } //*********addEventListener绑定的js代码********* let button2 = document.getElementById("btn2") //使用addEventListener()可为一个元素绑定多个事件 button2.addEventListener("mouseover", func1, false) button2.addEventListener("click", func2, false) button2.addEventListener("click", func3, false) function func1() { console.log(button2) } function func2() { console.log(Date()) } function func3() { console.log("---------------") } //使用removeEventListener(event,function)移除事件 // button2.removeEventListener("mouseover", func1) </script>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of There are several ways to add events to elements in javascript. For more information, please follow other related articles on the PHP Chinese website!