<body>
<button id="btn" style="width:200px;height:200px">
<p id="p" style="width:100px;height:100px;background:azure;"><p>Click</p></p>
</button>
<script type="text/javascript">
var btn = document.getElementById('btn');
var p = document.getElementById('p');
function clickHandeler (e) {
alert('hello');
}
function subClickHandeler (e) {
e = e || window.event;
if(e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
}
btn.addEventListener('click',clickHandeler,false);
p.addEventListener('click',subClickHandeler,false);
</script>
</body>
IE中点击p的时候还是会弹出hello,为什么?该怎么解决?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
原因是html标签嵌套问题:
button元素标签里面不能嵌套p元素标签,因为p元素的父元素必须是那些子元素为段落式元素的元素。
参考 WEB标准系列-HTML元素嵌套
题主的代码我测试的结果在FF和IE中都没有效果,在Chrome,Safari,Opera中可以,说明浏览器的容错能力不一样。
把button标签改为p标签就可以了……
为了弄清楚这个答案,我凌晨两点睡的,今天又弄了一上午,也是醉了……
IE 8- 不支持以
addEventListener()的方式来监听事件,而是采用attachEvent()来监听事件。一般可以借助一些库来帮助处理兼容性问题,如果自己写的话,加一个检查即可: