unbind onclick event for 'a' inside a div with onclick event

回眸只為那壹抹淺笑 提交于 2020-01-04 09:05:32

问题


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)



来源:https://stackoverflow.com/questions/5660751/unbind-onclick-event-for-a-inside-a-div-with-onclick-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!