javascript - 从父 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>
感谢您提前提供的所有帮助!
解决方案
您可以使用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()
推荐阅读
- sql - 使用 DISTINCT 显示独特的项目
- excel - Excel - 如果不包含特定文本并且不是空白,则有条件地格式化列中的单元格
- python - f2py.exe 在某处,但目录不在路径上
- reactjs - 如果异步操作已成功获取数据并更新状态,则也仅调度一次操作
- plotly-dash - 使用多页通用示例破折号 dcc.store?
- pandas - 模块“numpy”没有属性“ndarray”
- javascript - 从 iframe 接收事件侦听器后重定向父页面
- r - RStudio 中最新版 extReme R 包的问题
- c# - 如何让我的列表框包裹起来并显示为下拉列表
- ruby-on-rails - 如何在 QA 中预览 Rails 电子邮件?