unbind onclick event for 'a' inside a div

2019-07-20 15:44发布

问题:

html:

<div id="container">
<div class="desc">desc</div>
<a href="foo.php">foo</a>
</div>

js:

$('#container').click(function(){
    ...
    my_function();
    ...
});

This works when the user click inside container except for the a tag.

If the user click a tag, the click event fires. However, I want to disable self-defined click function for a tag. That is, link to the page without the onlick event.

This doesn't work:

$('#container :not(a)').click();

回答1:

Check if the event originates from the a tag, like so

$('#container').click(function(e){
    if ($(e.target).is('a')) return;
    ...
    my_function();
    ...
});


回答2:

Sounds like you want to prevent the default click event for A tags firing - use:

$('#container a').click(function(e) {
  e.preventDefault();
});

Edit

To prevent your event from firing if the user clicks a link:

$('#container').click(function(e) {
  if(e.target.tagName !== 'A') {
    my_function();
  }
});


回答3:

Attach a click event handler to your links to tell them to stop event bubbling after their own handler executes:

$("#container a").click(function(e) {
   e.stopPropagation();
})

The other solutions won't work with hyperlinks using images as an anchor. (target=object HTMLImageElement & tagName=DIV)