阻止href打开链接,但仍执行其他绑定事件 [英] Prevent href from opening link but still execute other bind events
问题描述
我想防止链接打开页面.所以我写了这个:
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...
}
我可以通过一些测试将动作添加到第一个事件中,但是有一种优雅的方法可以阻止 only href事件的执行吗?
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?
编辑
实际上可以,抱歉.参见@ raina77ow小提琴在这里工作: http://jsfiddle.net/HeFS6/
In fact it works, sorry. See @raina77ow fiddle working here: http://jsfiddle.net/HeFS6/
推荐答案
请改用return false
.您可以在此处中看到下面的代码.
Use return false
instead. You can see the code below working here.
$("a").click(function() {
return false;
});
$(".toolbar a").click(function() {
alert("Do something");
});
@ raina77ow 和本文所指出的,使用return false
与调用event.preventDefault()
以及调用event.stopPropagation()
相同.由于过去在某些代码上没有return false
时遇到了麻烦,所以我总是建议这样做.
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.
这篇关于阻止href打开链接,但仍执行其他绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!