【发布时间】:2016-06-14 13:30:49
【问题描述】:
请尝试以下示例。第一个锚点有一个定义为 href 的 URL。当我单击嵌套跨度(“heart”)时,浏览器会跟随链接,而我使用的是 stopPropagation() 方法。
当href 值设置为“#”时,如第二个示例所示,传播将正确停止。我在 Firefox 47 上进行测试,但我认为在 Chrome 中是一样的。
任何人都可以解释这种行为以及如何解决它(我只需要使用 1 个<a> 和一个嵌套元素(跨度)在里面)?
PS:如果<h3>变成<a>标签,请不要备注:这不是问题,HTML5允许我写这个。
PS 2:当我将此代码插入 jsFiddle 时,我没有遇到同样的问题。
我的 HTML5 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script
src="http://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$(function() {
$("a").on("click", function(e) {
alert("Link");
});
$("a span").on("click", function(e) {
e.preventDefault;
e.stopPropagation();
e.stopImmediatePropagation();
// Updated code : If I add this Ajax Request. the "return false" instruction doesn't work anymore
$.getJSON('http://www.w3schools.com/website/Customers_MYSQL.php', {
option1: ''
}, function(response) {
alert('Heart after getSon');
});
// Doesn't fix the problem if getJson before
return false;
}
);
});
</script>
<style type="text/css">
span {display:inline-block;width:30%;margin:0 auto;color:#fff;text-decoration:none;background-color:#000;}
</style>
</head>
<body>
<a href="http://www.ewample.com" style="display:inline-block;width:300px;height:300px;border:1px solid #999;text-align:center;">
<h3>Link with href</h3>
<br/>
<br/>
<br/>
<span>Heart</span>
<br/>
<br/>
<br/>
</a>
<a href="#" style="display:inline-block;width:300px;height:300px;border:1px solid #999;text-align:center;">
<h3>Link without href (only #)</h3>
<br/>
<br/>
<br/>
<span>Heart</span>
<br/>
<br/>
<br/>
</a>
</body>
</html>
【问题讨论】:
标签: javascript events nested stoppropagation