admin管理员组文章数量:1332389
I have a link that looks like this:
<a href="page.html" class="myLink">
Link text
<div class="toggle">x</div>
</a>
When they click on the x
in toggle I want to prevent the link from navigating, but if they do click on the Link Text
I want the link to navigate.
I tried this:
$('.toggle').click(function(event) { $(this).parents('a').preventDefault(); });
But it didn't seem to work.
I have a link that looks like this:
<a href="page.html" class="myLink">
Link text
<div class="toggle">x</div>
</a>
When they click on the x
in toggle I want to prevent the link from navigating, but if they do click on the Link Text
I want the link to navigate.
I tried this:
$('.toggle').click(function(event) { $(this).parents('a').preventDefault(); });
But it didn't seem to work.
Share Improve this question edited Mar 4, 2013 at 20:39 Denys Séguret 383k90 gold badges810 silver badges775 bronze badges asked Mar 4, 2013 at 20:33 TalonTalon 4,99510 gold badges44 silver badges57 bronze badges 1- 1 api.jquery./event.preventDefault will tell you it's a method of the event object, not the jQuery object. – Blazemonger Commented Mar 4, 2013 at 20:41
2 Answers
Reset to default 6To stop propagation from the clicked element to the outer a
, you'd have to call stopPropagation. But here you can simply return false ( which both stops propagation and prevents default behavior) :
$('.toggle').click(function(event) {
// do interesting things
return false
});
It is the event not the element that you need to fire the preventDefault() method upon.
$('.toggle').click(function (event) {
event.preventDefault();
});
This will stop the event from triggering but not propagating up the document.
$('.toggle').click(function (event) {
event.stopPropagation();
});
Is it's counterpart.
本文标签: javascriptHow to prevent default link behavior if element inside of link is clickedStack Overflow
版权声明:本文标题:javascript - How to prevent default link behavior if element inside of link is clicked - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742289899a2447599.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论