通过事件绑定,可以给控件添加多个事件
attachEvent(事件名, 函数)
detachEvent(事件名, 函数)
addEventListener(事件名, 函数, false)
removeEventListener(事件名, 函数, false)
Ex
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>事件绑定</title>
<script src="js/myAddEvent.js"></script>
<script>
window.onload = function(){
var btn = document.getElementById("btn");
myAddEvent(btn, "click", a);
myAddEvent(btn, "click", b);
myDelEvent(btn, "click", a);
myDelEvent(btn, "click", b);
}
function a(){
console.log("a");
}
function b(){
console.log("b");
}
</script>
</head>
<body>
<button id="btn">click</button>
</body>
</html>
共通方法
/**
* 添加绑定
*/
function myAddEvent(obj, ev, fn){
if(obj.attachEvent){
obj.attachEvent("on"+ev, fn);
}else{
obj.addEventListener(ev, fn, false);
}
}
/**
* 解除绑定
*/
function myDelEvent(obj, ev, fn){
if(obj.detachEvent){
obj.detachEvent("on"+ev, fn);
}else{
obj.removeEventListener(ev, fn, false);
}
}