简体   繁体   中英

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?

I tried 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(); instead. You are using event.preventDefault() on an element that has no default click behaviour, so it does nothing.

 $(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. 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();

And then finally, you'll need to test to make sure the element clicked was not the <a> ; So your code will look like this:

Here is a codepen that demonstrates this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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