The addEventListener() method is compatible with the writing of all browsers (event listener)

Internet Explorer 8 and earlier versions of IE do not support the addEventListener() method. We can define a method to be compatible with all browsers.

<script>
var x = document.getElementById("myBtn");
if (x.addEventListener) {                    // 所有主流浏览器,除了 IE 8 及更早版本
    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {                  // IE 8 及更早版本
    x.attachEvent("onclick", myFunction);
}
</script>

In order to be compatible with all browsers, we can define a function: call when there is addEventListener, and call attachEvent when there is no addEventListener.

/*
 * 参数:
 *     obj:要绑定事件的对象
 *     eventStr:事件(注意:这里不要on)
 *      callback:回调函数
 */
function bind(obj , eventStr , callback){
    if(obj.addEventListener){
        //大部分浏览器
        obj.addEventListener(eventStr , callback , false);
    }else{
        //IE8及以下
        obj.attachEvent("on"+eventStr , function(){
            //在匿名函数中调用回调函数
            callback.call(obj);
        });
    }
}   

Guess you like

Origin blog.csdn.net/Serena_tz/article/details/114115286