The content of this article is about the content analysis of DOM event binding in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
DOM level 2 event
element.addEventListener(type,handler,boolean)
The first value represents the event type, without adding on.
The second one is the execution method. (Event handling function)
The third value is a Boolean value, the default is false, and is only executed during the bubbling phase. true is executed in the capture phase
element.removeEventListener(type,handler,boolean)
The first value represents the event type, without on.
The second one is the execution method. (Event handling function)
The third value is a Boolean value, the default is false, and is only executed during the bubbling phase. true to execute the
removal event during the capture phase. Usage is consistent with addEventListener.
element.attachEvent(type,handler) IE event binding.
element.detachEvent(type, handler) IE event removal.
The first value represents the event type, plus on.
The second one is the execution method. (Event handling function),
Since IE’s event model only has a bubbling model, only two values need to be passed.
Add cross-browser event binding
var addEvent = function(ele,type,handler){ if(ele.addEventListener){ ele.addEventListener(type,handler,false) }else if(ele.attachEvent){ ele.attachEvent("on"+type,handler) }else{ ele["on"+type]=handler } } addEvent(btn,"click",function(){console.log("点击")})
Remove Cross-browser binding
function removeEvent(ele,type,handler){ if(ele.removeEventListener){ ele.removeEventListener(type,handler,false) } else if(ele.detachEvent){ ele.detachEvent('on'+type,handler) } else{ ele['on'+type]=null } } removeEvent(btn,"click",function(){console.log("点击")})
DOM level 0 event
on-attribute in HTML
<button id="btn" onclick="console.log(1)">确定</button> <button id="btn" onclick="fn()">确定</button>
The characters in quotation marks are executable strings
Because of the on-attribute in HTML The - method tightly couples js and HTML, which is not conducive to later maintenance, so it is not recommended.
var btn=document.getElementById("btn") btn.onclick=function(){ console.log(1); } btn.onclick=function(){ console.log(2); }//2
If you add the same event, the later one will overwrite the previous event
Related recommendations:
js Detailed explanation of DOM event binding
Detailed explanation of DOM event binding usage in JQuery_jquery
The above is the detailed content of Content analysis of DOM event binding in javascript. For more information, please follow other related articles on the PHP Chinese website!