Prevent href from opening link but still execute other bind events

天涯浪子 提交于 2020-04-07 21:59:12

问题


I want to prevent links from opening pages. So I have written this :

$("a").click(function(e) {
    e.preventDefault()
}

which is great! But this blocks my other event :

$(".toolbar a").click(function(e) {
    ...action...
}

Sure I can add my action to the first event with some test, but is there an elegant way to prevent only href event from executing?

EDIT

In fact it works, sorry. See @raina77ow fiddle working here: http://jsfiddle.net/HeFS6/


回答1:


Use return false instead. You can see the code below working here.

​$("a").click(function() {
    return false;
});

$(".toolbar a").click(function() {
    alert("Do something");
});​

As pointed by @raina77ow with this article, using return false is the same as calling event.preventDefault() and also event.stopPropagation(). As I had troubles without return false on some codes in the past, I always suggest it.

But the most importante thing here is the bind order: your last bind will be your first executed code. So, take care about it and go.




回答2:


In place of e.preventDefault(), have you tried return false? This should also prevent browser default behaviour.




回答3:


There is no href event. That is what you'd end up with if prevent default on click. You should just use more specific selectors.



来源:https://stackoverflow.com/questions/12299227/prevent-href-from-opening-link-but-still-execute-other-bind-events

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