jQuery 防止 href 打开链接但仍执行其他绑定事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12299227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:32:13  来源:igfitidea点击:

Prevent href from opening link but still execute other bind events

jqueryeventsclickpreventdefault

提问by Benoit R

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 onlyhref event from executing?

当然我可以通过一些测试将我的操作添加到第一个事件中,但是有没有一种优雅的方法来防止执行 href 事件?

EDIT

编辑

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

事实上它有效,对不起。见@raina77ow 小提琴在这里工作:http: //jsfiddle.net/HeFS6/

回答by Erick Petrucelli

Use return falseinstead. You can see the code below working here.

使用return false来代替。你可以在这里看到下面的代码。

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

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

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

正如@raina77ow本文中指出的那样, usingreturn false与调用event.preventDefault()event.stopPropagation(). 由于我return false过去在没有使用某些代码时遇到了麻烦,因此我总是建议这样做。

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.

但这里最重要的是绑定顺序:您的最后一次绑定将是您第一个执行的代码。所以,放心吧,去吧。

回答by Matt C

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

代替e.preventDefault(),你试过return false吗?这也应该防止浏览器默认行为。

回答by Hazem Salama

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.

没有 href 事件。如果阻止默认点击,这就是你最终会得到的结果。您应该只使用更具体的选择器。