Setting method: 1. Set through the event attribute in the HTML tag, the syntax is "on event name="handling function""; 2. Use "element.onclick" to set; 3. Use addEventListener( ) method to set.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Inline binding
Inline binding: in HTML The tag is bound through the event attribute. The binding method is: on event name. Then assign the triggered event to the attribute, as follows:
<button onclick="alert('123');">点击</button>
2. Use element.onclick Event binding
Use element.onclick for event binding: bind events to the DOM by manipulating DOM elements (using form intra-peer binding).
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> window.onload = function(){ var btn = document.getElementById('btn'); btn.onclick = function(){ alert("hello world"); } } </script> </head> <body> <button id="btn">点击</button> </body> </html>
3. Use the addEventListener() method
Use the addEventListener() method, accepting 3 parameters (the name of the event to be processed, as The function of the event handler, a Boolean value. If this Boolean value is true, it means that the event handler is called in the event capture phase, if it is false, it is called in the event bubbling phase). Some browsers do not support event capture (such as IE8 and lower), so be careful about binding event listeners during the capture phase.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> window.onload = function(){ var btn = document.getElementById('btn'); btn.addEventListener('click',function(){ alert("123"); },false); } </script> </head> <body> <button id="btn">点击</button> </body> </html>
Method to unbind an event: call removeEventListener() through the element to remove it. The parameters passed in are the same as when adding the event handler. The second parameter (event handler function) must be the same ( point to the same address), so the event handler function should be saved in a variable. If the anonymous function is passed in, the event listener cannot be removed.
Note: In IE8 and below versions, use attachEvent() for event binding, accepting 2 parameters (event handler name, event handler function). The event handler bound by this method will Executed during the bubbling phase. This method can bind multiple event handlers, but the execution order is reversed from the binding order.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to set up event listening in javascript. For more information, please follow other related articles on the PHP Chinese website!