How to prevent default event firing but still allow event to bubble

 ̄綄美尐妖づ 提交于 2019-12-10 12:49:25

问题


Using jQuery: with the following code I'd like to prevent the href url (in this case a hash '#') being fired on click, but still allow the click event to continue bubbling up the chain. How can this be achieved please?

<div>
    <a href="#">Test</a>
</div>

$('a').click(function(e){
    // stop a.click firing but allow click event to continue bubbling?
});

回答1:


$('a').click(function(e){
    e.preventDefault();
    // stop a.click firing but allow click event to continue bubbling?
});

e.preventDefault() won't prevent bubbling, e.stopPropagation() or return false (stop both) will.




回答2:


You could do:

$('a').click(function(e){
     e.preventDefault();
    // stop a.click firing but allow click event to continue bubbling?

});

fiddle here http://jsfiddle.net/tU53v/




回答3:


try this..

$('a').click(function(e){
     e.preventDefault();
    // stop a.click firing but allow click event to continue bubbling?

});

here you can find difference between return false and e.preventDefault();



来源:https://stackoverflow.com/questions/6745618/how-to-prevent-default-event-firing-but-still-allow-event-to-bubble

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