Detailed JavaScript event listeners

Detailed JavaScript event listeners

JavaScript event listeners must first understand the following principles:

  1. Listen for events function can not be brought into any arguments

  2. Listening for events and only one function parameter e is the event object to the event sink, no other functions

  3. Event function can not return to write the return value, but can return jump

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:

When an event is no longer used elements must be removed, otherwise it will cause memory accumulation, listen for events will be stored on the heap; when the element is deleted, must delete all the events that element.
 

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

Guess you like

Origin www.cnblogs.com/tokkipopo/p/12657311.html
Recommended