简体   繁体   English

通过点击内部禁用 HREF

[英]Disable HREF by onclick inside

How can I disable the a href if an element with an onclick function is fired within the <a> element?如果在<a>元素中触发了具有onclick函数的元素,如何禁用 a href

I tried event.preventDefault();我试过event.preventDefault(); , but it doesn't seem to do anything. ,但它似乎没有任何作用。
How can I solve this?我该如何解决这个问题?

 $(function() { $(".inside > .fa").click(function(event) { event.preventDefault(); alert("TEST"); }); });
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='/'> <div class='button'> <div class='inside'> <i class="fa fa-globe"></i> </div> </div> </a>

The click still bubbles upwards.咔哒声仍然向上冒泡。 Use event.stopPropagation();使用event.stopPropagation(); instead.反而。 You are using event.preventDefault() on an element that has no default click behaviour, so it does nothing.您在没有默认单击行为的元素上使用event.preventDefault() ,因此它什么都不做。

 $(function() { $(".inside > .fa").click(function(e) { e.stopPropagation(); console.log(e.target); }); });
 a { display: block; /* required otherwise you cannot have block level elements like div inside a */ }
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='https://google.com' target="_top"> <div class='button'> <div class='inside'> <i class="fa fa-globe"></i> </div> </div> </a>

尝试return false而不是event.preventDefault()来停止事件冒泡

Register your event listener on the <a> tag.<a>标记上注册您的事件侦听器。 And the make the changes below.并在下面进行更改。 This takes advantage of Event Delegation (a good thing).这利用了事件委托(一件好事)。

you'll need both of these:你将需要这两个:

event.preventDefault();

Add添加

event.stopPropagation(); event.stopPropagation();

And then finally, you'll need to test to make sure the element clicked was not the <a> ;最后,您需要进行测试以确保点击的元素不是<a> So your code will look like this:所以你的代码看起来像这样:

Here is a codepen that demonstrates this:这是一个演示这一点的代码笔:

https://codepen.io/anon/pen/NyJgWB?editors=1111 https://codepen.io/anon/pen/NyJgWB?editors=1111

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM