子div单击事件触发父单击事件

时间:2013-10-22 23:11:23

标签: javascript

如果单击子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');
}

1 个答案:

答案 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');
}