jquery - jQuery - e.stopPropagation() 在动态内容上取消 e.preventDefault()
问题描述
我刚刚遇到了这个相当烦人的问题,我真的错过了一些关于为什么会发生这种行为的解释——最重要的是如何绕过它。
我有一些在某个事件上使用 jQuery 创建的动态内容。创建内容时,会on("click")
向元素添加一个事件侦听器,以停止元素的传播:e.stopPropagation()
。
但是,由于元素包含我希望控制的锚标签,我想e.preventDefault()
在锚标签中添加一个 - 但是它似乎e.stopPropagation()
取消了e.preventDefault()
.
该问题在下面重新创建:
$(document).on("click", ".test-a, .test-b", function(e){
e.preventDefault();
alert("test");
});
$("body").append('<a class="test-a" href="#">Click this to see what happens when e.stopPropgation() is active (nothing)</a>');
$("body").append('<a class="test-b" href="#">Click this to see what happens when only e.preventDefault() is active</a>');
$(".test-a").on("click", function(e){
e.stopPropagation();
})
a{
display:block;
margin-bottom: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
解决方案
推荐阅读
- javascript - 如何在 Laravel 中删除 app.js 但保留 vue.js?
- r - 函数 highcharter::hciconarray 在 R 中不起作用
- excel - 循环数组时出现类型不匹配错误
- android - 我在 content_main 中的设计视图总是空的。当我尝试删除按钮或 textView 时,它会缩小到左上角
- java - 在这种情况下如何使用 HashMap?
- powershell - collections.ArrayList Add 方法在第一次添加时产生一个字符串
- laravel - 如何从迁移中创建 Laravel 模型?
- angular - 无法获取变量
- azure - 通过子网连接 CosmosDB 并定义相应的连接字符串
- python - 重命名 Python Spark 数据框列名称或为其赋予别名