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

Dan*_*ink 44 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

Ade*_*eel 92

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

   if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
Run Code Online (Sandbox Code Playgroud)


Tim*_*man 18

这里查看有关事件传播的信息

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

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();
}
Run Code Online (Sandbox Code Playgroud)


小智 6

只需添加此代码:

window.event.stopPropagation();
Run Code Online (Sandbox Code Playgroud)


Tat*_*nen 5

return false; 来自内部div的onclick功能:

<div onclick="alert('inner'); return false;" ...
Run Code Online (Sandbox Code Playgroud)

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


rah*_*hul 5

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

您可以使用

e.cancelBubble = true; //IE
Run Code Online (Sandbox Code Playgroud)

e.stopPropagation(); //FF
Run Code Online (Sandbox Code Playgroud)


小智 5

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

<div onclick="alert('inner'); event.stopPropagation;" ...
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但像这样: onclick="alert('inner'); event.stopPropagation();" (3认同)