bind解决事件绑定的兼容性问题。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
/*
* 定义一个通用的绑定响应函数的方法
* 参数:
* obj表示要绑定响应函数的对象
* eventStr事件的名字(不要on)
* callback回调函数
*
*/
function bind(obj , eventStr , callback){
//判断对象中是否含有addEventListener
if(obj.addEventListener){
//正常浏览器的方式
//正常浏览器中this是obj
obj.addEventListener(eventStr,callback,false);
}else{
//IE的方式
//IE中是window
//修改callback中的this为obj,this是谁由函数的调用方式决定
obj.attachEvent("on"+eventStr,function(){
//在匿名函数中我们来调用回调函数如果没有匿名函数,直接把callback放在参数位置上,则无法使用call来指定调用对象,均由浏览器调用。
callback.call(obj);
});
}
}
window.onload = function(){
var btn01 = document.getElementById("btn01");
bind(btn01, "click" , function(){
alert(this); //用匿名函数传入callback
});
};
</script>
</head>
<body>
<button id="btn01">按钮</button>
</body>
</html>