我想要一个带有 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>
- 注意:虽然它在代码段编辑器中似乎可以正常工作,但在完整页面中,浏览器确实会转到 Google。
最佳答案
您不需要所有这些,只需将 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>
关于javascript - jQuery触发anchor的onclick事件而不发送浏览器到href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49160821/