最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop propagation of click event on href - Stack Overflow

programmeradmin0浏览0评论

How can I stop the propagation of the click event so that the browser will NOT redirect?

<a id="theHref" href="/">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>

How can I stop the propagation of the click event so that the browser will NOT redirect?

<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>
Share Improve this question edited May 14, 2021 at 15:16 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 28, 2015 at 9:35 nagy.zsolt.hunnagy.zsolt.hun 6,69416 gold badges64 silver badges102 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

Firstly, you want to listen on the "click" event, not mousedown

document.getElementById("theHref").addEventListener("click", function(event) {
    console.log("href clicked, lets try to stop event propagation");
    event.preventDefault();
    return false;
});

not sure you need the return false - I can never remember cross browser nuances like that :p return false does NOT stop Firefox, for instance

Just try by using return false that is the simple method which will not make you redirect

<script>
$(function(){   
$("#theHref").click(function(){
  return false;
});
});
</script>

Just refer this fiddle Fiddle

This should work:

document.getElementById("theHref").addEventListener("click", function(event) {
    console.log("href clicked, lets try to stop event propagation");
    event.preventDefault();
});

Try this.

<a href="https://www.google.com/" onclick="event.stopPropagation()">Click Here</a>

there is a default event object available on elements. You can access it to disable/stop the event propagation.

发布评论

评论列表(0)

  1. 暂无评论