如果单击子 div,如何防止父单击事件触发?
var p = document.getElementById('parent');
var c = document.getElementById('child');
p.onclick = function () {
alert('parent click');
}
c.onclick = function () {
alert('child click');
}
如果单击子 div,如何防止父单击事件触发?
var p = document.getElementById('parent');
var c = document.getElementById('child');
p.onclick = function () {
alert('parent click');
}
c.onclick = function () {
alert('child click');
}
在孩子的处理程序中调用对象的.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');
}