标签:
var addEvent = function() {
//属于方法检测,判断window是否有该方法
if(window.addEventListener) {
return function f1(target, type, handler) {
target.addEventListener(type, handler);
};
} else if(window.attachEvent) {
return function f2(target, type, handler) {
target.attachEvent("on" + type, function() {
handler.apply(target);//因为this默认指向window,所以通过apply方法来改变this的指向问题
//apply使用方法:function.apply(第一个参数,第二个参数)
// 第一个参数:表示指向那个对象来调用函数
// 第二个参数:是一个数组或者是伪数组的对象 (这个参数是可选的)
这个数组中的每一项的值,都将作为被调用函数的参数
});
};
} else {
return function f3(target, type, handler) {
target["on" + type] = handler;
};
}
}();
//封装事件兼容函数使用到了闭包技术,目的是:当在页面中多次调用该函数,可以避免重复判断,提高js执行效率。
标签:
原文地址:http://www.cnblogs.com/lsy0403/p/5862850.html