Detailed JavaScript event listeners
JavaScript event listeners must first understand the following principles:
-
Listen for events function can not be brought into any arguments
-
Listening for events and only one function parameter e is the event object to the event sink, no other functions
-
grammar
Add an event
element.addEventListener ( 'event name', the event function name, event bubbling / capture);
Remove event
element.removeEventListener ( 'event name', the event function name, event bubbling / capture);
When the browser ie8 and below, respectively, shall be as follows:
element.attachEvent ( 'on the beginning of the event name', the event function name);
element.detachEvent ( 'ON at the beginning of the event name', the event function name);
Case
var num=0; var bn=document.querySelector("button"); bn.addEventListener("click",clickHandler1); bn.addEventListener("click",clickHandler2); bn.addEventListener("mousemove",clickHandler2); function clickHandler1(e){ num++; console.log("aaa"); if(num>1){ // this是事件侦听的对象 // e.currentTarget.removeEventListener("click",clickHandler1); this.removeEventListener("click",clickHandler1); } } function clickHandler2(e){ // console.log("bbb"); console.log(e.type) }
have to be aware of is:
P.S
DOM0 level:
▪ a label of the same event can only bind one event function
▪ events can be added directly inline
▪ major browsers are supported, there is no compatibility issues
DOM2 level
▪ a label of the same event can bind multiple event function
▪ binding event function must have a name, otherwise it can not be deleted
▪ compatibility issues, IE8 and earlier wording and a standard browser wording is not the same