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);
});

猜你喜欢

转载自www.cnblogs.com/lac759/p/10556268.html