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

IT技术 javascript html onclick
2021-03-14 13:22:06

只是一个简单的问题。我在使用 div 和 onclick javascript 时遇到问题。当我点击内部 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>
6个回答

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

   if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
谢谢。优秀的回答;正是我要找的。
2021-05-01 13:22:06

此处查看有关事件传播的信息

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

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();
}

只需添加此代码:

window.event.stopPropagation();
这对我不起作用。上面的答案更准确。
2021-05-10 13:22:06

return false; 来自内部 div 的 onclick 函数:

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

您正在处理的内容称为事件传播

您建议的方法实际上不起作用。(至少不是在我刚刚仔细检查过的任何浏览器中 - Firefox 3.6,IE8。)请注意,您的链接实际上说要使用不同的方法,我在回答中给出了该方法。
2021-04-30 13:22:06

这是一个事件冒泡的例子。

您可以使用

e.cancelBubble = true; //IE

e.stopPropagation(); //FF