2

我该怎么做:

<div onclick="foo1()">
    <div onclick="foo2()"></div>
</div>

当我这样做并单击子元素时,它仍然运行 foo1() 函数。如何暂时禁用父元素或其他东西?

4

4 回答 4

3

使用 jQuery,您可以使用:http ://api.jquery.com/event.stopPropagation/

于 2013-08-05T02:29:41.943 回答
1

我为您创建了一个工作示例

HTML

<div id="parent">
    <div id="child"></div>
</div>

CSS(只是为了区分两个div)

#parent {
    background-color: black;
    width: 220px;
    height: 220px;
}

#child {
    position:relative;
    background-color: blue;
    width: 110px;
    height: 110px;
    top:160px;
    left:160px;
}

JavaScript(包括 jQuery)

$(document).ready(function(){
    $('#child').click(function() {
        alert('Child');
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    });
    $('#parent').click(function() {
        alert('Parent');
    });
});

当您单击孩子时,只有孩子的动作才会被执行。您可以根据需要修改我的示例以实现所需的功能。

希望这对你有用。

于 2013-08-05T03:44:24.227 回答
1

是的,jQuery 可以解决您的问题。请看下面的代码:

<script src="jquery.js" type="text/javascript"></script>
<script>
function a()
{
    alert('parent');
}

$(document).ready(function(){
    $('#div2').click(function(e){alert('child');e.stopPropagation();})
})
</script>
<div onclick="a();" style="height:100px;width:100px;border:1px solid red">
    <div id="div2" style="height:85px;width:85px;border:1px solid green">
    </div>
</div>
于 2013-08-05T02:41:05.407 回答
-1

你可以试试

<div onclick="foo1(event)">
    parent
    <div onclick="foo2(event)">child</div>
</div>

function foo1(e){
    console.log('foo1', e)
}

function foo2(e){
    e.stopPropagation();
    console.log('foo2', e)
}

演示:小提琴

于 2013-08-05T02:45:11.230 回答