您可以看到下面的代码,我有两个事件:

在父级dblclick上的1- target1

儿童dblclick上的2- target2

预期结果:当我在子级dblclick上运行target2时,我不想在dblclick上运行target1事件。我怎样才能做到这一点?



$("#target1").dblclick(function() {
  console.log("I don't want this click when dbclick on target2.");
});
$("#target2").dblclick(function() {
  console.log("Click 2.");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Screenshot" style="height:200px; width:300px;">
  <table style="width:100%;">
    <tr>
      <td id="target1">
        target1
        <p id="target2">target2 </p>
      </td>
    </tr>
  </table>
</div>

最佳答案

您可以将e(事件)参数添加到第二单击功能,然后在第二单击事件中使用e.stopPropagation();。这样可以防止单击事件冒泡,并防止单击子元素时运行父单击功能。



$("#target1").dblclick(function() {
  console.log("I don't want this click when dbclick on target2.");
});

$("#target2").dblclick(function(e) {
  console.log("Click 2.");
  e.stopPropagation();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Screenshot" style="height:200px; width:300px;">
  <table style="width:100%;">
    <tr>
      <td id="target1">
        target1
        <p id="target2">target2 </p>
      </td>
    </tr>
  </table>
</div>

09-20 09:19