How JS how to bind multiple events as an element?

onclick () The wording is DOM0 level writing specification is supported by all browsers, but such an approach has not bind multiple events at the same time, make the code coupling together of the state. But addEventListener () method is defined in DOM2 standard, it is possible to control the capture phase or in the event is to call an event handler for the bubbling phase. Since this is DOM2 defined in the standard, then the only browser that supports DOM2-level event handler only support this approach (IE9, Firefox, Safari, Chrome and Opera support).

A, onclick () mode

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>绑定多个事件</title>
 6     <script>
 7         window.onload = function(){
 8             document.getElementById('btn').onclick = function () {
 9                 alert(1);
10             };
11             document.getElementById('btn').onclick = function () {
12                 alert(2);
13             };
14         }
15     </script>
16 </head>
17 <body>
18 <button id="btn">点我</button>
19 </body>
20 </html>

 

The result is the second run the first onclick onclick to cover, although in most cases can be completed with the results you want on, but sometimes they need to do more of the same event, it is clear that if not completed on

Two, addEventListener () method

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>绑定多个事件</title>
 6     <script>
 7         window.onload = function(){
 8             document.getElementById('btn').addEventListener('click', function(){
 9                 alert(1);
10             }, false);
11             document.getElementById('btn').addEventListener('click', function(){
12                 alert(2);
13             }, false);
14         }
15     </script>
16 </head>
17 <body>
18 <button id="btn">点我</button>
19 </body>
20 </html>

addEventListenert method first parameter to fill in the name of the event, the second parameter is a function of the third parameter is the capture phase or the bubbling phase processing event handler. true representatives of the capture stage process, false on behalf of the bubbling stage of the process. The third parameter can be omitted in most cases do not need to use the third argument, do not write the third parameter default false

Guess you like

Origin www.cnblogs.com/anjing940/p/11016790.html
Recommended