阻止 Javascript 中的事件

Prevent Events in Javascript

我有两个 div,外部 Div 和内部 Div,两个 div 都带有点击事件。 每当我单击内部 div 时,它也会提醒外部 div,我想在单击 Javascript 中的内部 Div 时阻止外部 div 的事件处理程序

这是我的Javascript

function funOne()
{
   //event.stopPropagation();
   alert('Outer Div')
}

function funTwo()
{
  //event.stopPropagation();
  alert('Inner Div')
}

这里是DEMO

使用 stopPropagation 应该可以阻止从子 div 到父 div 的传播,但是您的函数缺少事件对象。

function funOne(e)
{
    e.stopPropagation();
    alert('Outer Div')
}

function funTwo(e)
{
    e.stopPropagation();
    alert('Inner Div')
}

调用函数时还需要传递事件:

<div class="first" onclick="funOne(event)">
    <div class="second" onclick="funTwo(event)"></div>
</div>

请注意,stopPropagation 仅适用于 child/parent 情况。如果 div 只是 出现 在另一个 div 中,stopPropagation 什么都不做。

在此处检查您错过了定义的事件。

function funOne(e)
{
    e.stopPropagation();
    alert('Outer Div')
}

function funTwo(e)
{
    e.stopPropagation();
    alert('Inner Div')
}
.first{width:600px; height:600px; background:yellow}
.second{width:100px; height:100px; background:orange; position:relative; top:50%; left:50%; margin-left:-50px; margin-top:-50px}
<div class="first" onclick="funOne(event)">
 <div class="second" onclick="funTwo(event)"></div>
</div>

勾选Fiddle.

更新了您的 fiddle 检查一下:

<div class="second" onclick="funTwo(event)"></div>

function funTwo(event)
{
event.stopPropagation();
alert('Inner Div')
}

https://jsfiddle.net/7r4hhzo0/4/

<script>
  function funOne(e)
  {
     e.stopPropagation();
    alert('Outer Div')
  }

   function funTwo(e)
    {
      e.stopPropagation();
     alert('Inner Div')
  }
   </script>

您需要调用这些函数,例如 onclick="funOne(event);" 和 onclick="funTwo(event);"