The difference and compatibility of javascript event binding

The difference and compatibility between DOM0 level binding and DOM2 level binding

1. Difference

  1. The on event supports compatibility with any browser, addEventListener only supports IE8 and above

  2. The on event actually binds a fixed attribute to the DOM. For example, onclick is to bind an anonymous function to the element, which means that the original attribute value will be overwritten when assigning again, and addEventListener is the callback function used. Setting multiple event callback functions will not be overwritten

     bn.onclick=function(){
          
          
                console.log("aa");
                // 这里时当点击时调用的匿名函数
            }
            bn.onclick=function(){
          
          
                console.log("bb");
            }
    
  3. The on event uses an anonymous function, which will lead to callback hell easily during development. Using addEventListener can effectively control the generation of callback hell.

     var div0=document.querySelector(".div0");
            var div1=document.querySelector(".div1");
            var div2=document.querySelector(".div2");
            var div3=document.querySelector(".div3");
            var div4=document.querySelector(".div4");
            div1.onclick=function(){
          
          
                div2.onclick=function(){
          
          
                    div3.onclick=function(){
          
          
                        div4.onclick=function(){
          
          
                            console.log("aaa");
                        }
                    }
                }
            }
    
    
  4. The on event does not support the capture phase, while addEventListener supports the capture phase event and once (the function is executed once and then destroyed)

  5. The method of deletion is different. On event use: null form deletion, addEventListener uses removeEventListener to delete the event

  6. The on event is the default event type of the system, and addEventListener can set a custom trigger event

    var btn = document.querySelector('button');
            btn.addEventListener('dianji',function() {
          
          
                console.log('我被触发了');
            })
            var  evt = new Event('dianji');//创建自定义事件
            btn.dispatchEvent(evt);//触发自定义事件
    //先监听后触发
    

2. Handling compatible


        function addEvent(elem,type,callback,bool){
    
    
          //如果没有传入bool则默认为捕获
            if(bool==undefined) bool=false;
            if(elem.addEventListener){
    
    
                elem.addEventListener(type,callback,bool);
            }else{
    
    
                elem.attachEvent("on"+type,callback);
            }
        }
       

Guess you like

Origin blog.csdn.net/chen_junfeng/article/details/109168309