js注册事件的on addEventListener attachEvent的区别和兼容性

时间:2019-03-19
本文章向大家介绍js注册事件的on addEventListener attachEvent的区别和兼容性,主要包括js注册事件的on addEventListener attachEvent的区别和兼容性使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

用on绑定 第二个事件会覆盖前者

   <button type="" id="bu">点我</button>

   button=document.getElementById('bu');

   <script>

      button.onclick=function(){alert(1)};

      button.onclick=function(){alert(2)};

   </script>

要同时运行两个事件则需要用addEventListener

  <script>

    button.addEventListener('click', function(){alert(1);});

    button.addEventListener('click',function(){alert(2);});

  </script>

addEventListener IE8版本不支持  可以使用 attachEvent绑定事件 attachEvent事件必须带on

  <script>

    button.attachEvent('onclick', function(){alert(1);});

    button.attachEvent('onclick',function(){alert(2);});

  </script>

  兼容性写法

  

function addEvent(element,eventName,fn){

   if(element.addEventListener){

  element.addEventListener(eventName,fn);

    }else if(element.attachEvent){
      element.attachEvent("on"+eventName,fn);

    }

}
addEvent(bid,'click',function(){
alert(1);
});