<html>
<body>
<button id="myButton" onclick="changeBg();">点击变色</button>
<button onclick="detachFunction();">DetachFunction</button>
<script language="javascript">
function changeBg(){
document.bgColor = 'red';
}
function detachFunction() {
document.bgColor = 'white';
document.getElementById("myButton").detachEvent('onclick', changeBg);
}
</script>
</body>
</html>IE9对于写在html标签中进行绑定的事件无法用detachEvent取消绑定。
测试发现动态绑定的事件,才能动态取消绑定
<html>
<body>
<button id="myButton">点击变色</button>
<button onclick="attachFunction();">AttachFunction</button>
<button onclick="detachFunction();">DetachFunction</button>
<script language="javascript">
function changeBg(){
document.bgColor = 'red';
}
function attachFunction(){
document.getElementById("myButton").attachEvent("onclick", changeBg);
}
function detachFunction() {
document.bgColor = 'white';
document.getElementById("myButton").detachEvent('onclick', changeBg);
}
</script>
</body>
</html>
本文探讨了在IE9浏览器中使用JavaScript进行事件绑定的方法,并特别关注如何在静态与动态绑定事件的情况下实现事件的取消绑定。通过两个示例展示了直接在HTML标签中绑定事件与通过JavaScript动态绑定事件的区别。
4353

被折叠的 条评论
为什么被折叠?



