阻止href打开链接,但仍执行其他绑定事件 [英] Prevent href from opening link but still execute other bind events

查看:105
本文介绍了阻止href打开链接,但仍执行其他绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止链接打开页面.所以我写了这个:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆