一、知识要点
可以重复绑定相同事件,避免事件被覆盖
二、源码参考
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
window.onload = function() {
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
// 绑定方式一
btn1.onclick = function() {
alert('绑定方式一~onclick')
}
// 绑定方式二
if(btn2.attachEvent) {
btn2.attachEvent('onclick', function() {
alert('绑定方式二~attachEvent');
})
} else {
btn2.addEventListener('click', function() {
alert('绑定方式二~addEventListener');
}, false)
}
}
</script>
</head>
<body>
<input type="button" name="btn1" id="btn1" value="点击1" />
<input type="button" name="btn2" id="btn2" value="点击2" />
</body>
</html>
封装
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
// 封装成通用方法
function myAddEvent(obj, ev, fn) {
if (obj.attachEvent) {
obj.attachEvent('on' + ev, fn); // IE onclick
} else {
obj.addEventListener(ev, fn, false); // 非IE click
}
}
window.onload = function () {
var oBtn = document.getElementById('btn1');
myAddEvent(oBtn, 'click', function () {
alert('a');
});
myAddEvent(oBtn, 'click', function () {
alert('b');
});
};
</script>
</head>
<body>
<input id="btn1" type="button" value="按钮" />
</body>
</html>