首页 > 解决方案 > 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>

标签: jquerypreventdefaultstoppropagation

解决方案


推荐阅读