0

如果单击子 div,如何防止父单击事件触发?

http://jsfiddle.net/2GEKu/

var p = document.getElementById('parent');
var c = document.getElementById('child');

p.onclick = function () {
    alert('parent click');
}
c.onclick = function () {
    alert('child click');
}
4

1 回答 1

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');
}
于 2013-10-22T23:12:17.900 回答