如果单击子div,如何防止触发父点击事件?
var p = document.getElementById('parent');
var c = document.getElementById('child');
p.onclick = function () {
alert('parent click');
}
c.onclick = function () {
alert('child click');
}
答案 0 :(得分:3)
在子处理程序中调用.stopPropagation()
对象的event
方法。
var p = document.getElementById('parent');
var c = document.getElementById('child');
p.onclick = function () {
alert('parent click');
}
c.onclick = function (event) {
event.stopPropagation();
alert('child click');
}
要使其与IE8及更低版本兼容,请执行以下操作:
c.onclick = function (event) {
if (event)
event.stopPropagation();
else
window.event.cancelBubble = true;
alert('child click');
}