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
Add a ment  | 

2 Answers 2

Reset to default 6

To 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