首页 > 解决方案 > 从父 div 的子级禁用单击事件

问题描述

我正在尝试将单击事件添加到div具有类父级的事件中。现在在里面div我有一个div有自己的点击事件的班级孩子。

我怎样才能设法禁用该子元素的父函数的单击事件以执行子元素本身的功能?

我尝试过使用pointer-event:none;,但它似乎不起作用。为了更好地理解,我写了一个 jsfiddle。

https://jsfiddle.net/arq1epbs/

$(document).on('click', '.parent', function() {
  var url = $(this).attr("data-url")
  document.location.href = url
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent" data-url="www.google.com">
  Im the parent
  <div class="child">
    im the child and I don't want to go to Google
  </div>
</div>

感谢您提前提供的所有帮助!

标签: javascripthtmljquerycss

解决方案


您可以使用stopPropagation()

 $(document).on('click', '.parent', function () {
    var url = $(this).attr("data-url")
    document.location.href = url 
});
 $(document).on('click', '.child', function (e) {
 e.stopPropagation();
});

由于它在堆栈片段中不起作用,这里有一个小提琴 供参考:stopPropagation()


推荐阅读