js绑定事件兼容性写法

<html>
<body>
<div id="div1">点我绑定事件</div>
<script>
var addEvent = function( elem, type, handler ){

  //重写addEvent的好处是下一次调用时不会再走if判断,提高了一部分性能
  if ( window.addEventListener ){
    addEvent
= function( elem, type, handler ){       elem.addEventListener( type, handler, false );     }   }else if ( window.attachEvent ){     addEvent = function( elem, type, handler ){       elem.attachEvent( 'on' + type, handler );     }   }   addEvent( elem, type, handler ); }; var div = document.getElementById( 'div1' ); addEvent( div, 'click', function(){   alert (1); }); addEvent( div, 'click', function(){   alert (2); }); </script> </body> </html>

猜你喜欢

转载自www.cnblogs.com/huang-gua/p/10067342.html