[英]How to stop event propagation from within an anchor's href attribute without using onclick or onmousedown
[英]JQuery trigger anchor's onclick event without sending browser to href
我想要a
带有href
和onclick
函数a
标签,但是当用户单击链接时,我不希望浏览器转到href
而只是执行onclick
。 我尝试了以下方法:
function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; } $('.testClass').click(function(event) { $(this).trigger("onclick"); event.preventDefault(); });
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a> <div id="testDiv"></div>
您不需要所有这些,只需将return false添加到onclick处理程序即可:
function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; return false; }
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a> <div id="testDiv"></div>
您的问题是两次触发单击,首先是单击元素,然后是发生单击,因此您应在防止默认设置后将其他功能放到第一位。 使用event.preventDefault();
我将此行<a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a>
替换为此<a href="http://www.google.com" class="testClass" >click me</a>
然后修改脚本
function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; } $('.testClass').click(function(event) { event.preventDefault(); testFunc(); });
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass">click me</a> <div id="testDiv"></div>
这样说:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</head>
<body>
<a href="http://www.google.com" class="testClass">click me</a>
<div id="testDiv"></div>
<script>
function testFunc() {
document.getElementById("testDiv").innerHTML = "it works!";
}
$('.testClass').click(function(event) {
event.preventDefault();
testFunc();
});
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.