如何:使用onclick javascript在另一个div中使用onclick进行div

时间:2010-03-05 07:14:03

标签: javascript html onclick

只是一个简单的问题。我在使用onclick javascript的div中遇到问题。当我点击内部div时,它应该只触发它的onclick javascript,但外部div的javascript也被触发了。如何在不触发外部div的javascript的情况下点击内部div?

<html>
<body>
<div onclick="alert('outer');" style="width:300px;height:300px;background-color:green;padding:5px;">outer div
    <div onclick="alert('inner');"  style="width:200px;height:200px;background-color:white;" />inner div</div>
</div>
</div>
</body>
</html>

11 个答案:

答案 0 :(得分:89)

基本上javascript中有两个事件模型。 事件捕获事件冒泡。在事件冒泡中,如果单击div内部,则首先触发内部div单击事件,然后单击外部div单击。在事件捕获中,首先触发外部div事件,然后触发内部div事件。要停止事件传播,请在单击方法中使用此代码。

   if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

答案 1 :(得分:18)

查看有关事件传播的信息here

特别是你需要在事件处理程序中使用这样的代码来阻止事件传播:

function myClickHandler(e)
{
    // Here you'll do whatever you want to happen when they click

    // now this part stops the click from propagating
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

答案 2 :(得分:6)

只需添加以下代码:

window.event.stopPropagation();

答案 3 :(得分:5)

来自内部div的onclick函数的

return false;

<div onclick="alert('inner'); return false;" ...

您正在处理的内容称为event propagation

答案 4 :(得分:3)

这是事件冒泡的情况。

您可以使用

e.cancelBubble = true; //IE

e.stopPropagation(); //FF

答案 5 :(得分:2)

基于webkit的浏览器的另一种方法:

<div onclick="alert('inner'); event.stopPropagation;" ...

答案 6 :(得分:0)

Here是一些帮助您理解javascript事件冒泡的参考资料。

答案 7 :(得分:0)

答案 8 :(得分:0)

这非常有帮助,但它对我没用。

我所做的是here

所以我在外部onclick事件中添加了一个条件:

if( !event.isPropagationStopped() ) {
    window.location.href = url;
}

答案 9 :(得分:0)

您可以使用

    $("divOrClassThatYouDontWantToPropagate").click(function( event ) {
      event.stopPropagation();
    });

答案 10 :(得分:0)

这在Jquery中对我有用:

$('#outer_element').click(function(event) {
    if(event.target !== event.currentTarget) return;
    alert("Outer element is clicked")                       
});

这样,如果当前目标与外部div不同,它将不执行任何操作。您可以在子元素上实现常规函数。