[英]Stop propagation of click event on href
如何停止点击事件的传播,以便浏览器不会重定向?
<a id="theHref" href="http://stackoverflow.com/">SO</a>
<script>
document.getElementById("theHref").addEventListener("mousedown", function(event) {
console.log("href clicked, lets try to stop event propagation");
event.stopPropagation();
event.preventDefault();
return false;
});
</script>
首先,您要监听“click”事件,而不是 mousedown
document.getElementById("theHref").addEventListener("click", function(event) {
console.log("href clicked, lets try to stop event propagation");
event.preventDefault();
return false;
});
不确定您是否需要 return false - 我永远不会记得像这样的跨浏览器细微差别 :p return false 不会停止 Firefox,例如
只需尝试使用 return false ,这是一种不会让您重定向的简单方法
<script>
$(function(){
$("#theHref").click(function(){
return false;
});
});
</script>
只需参考这个小提琴Fiddle
这应该有效:
document.getElementById("theHref").addEventListener("click", function(event) {
console.log("href clicked, lets try to stop event propagation");
event.preventDefault();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.