javascript 有没有办法阻止默认事件,然后用 jQuery 再次触发它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6061126/
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
Is there any way to prevent default event and then fire it again with jQuery?
提问by Dimskiy
Basically I have an anchor element, <a href='bla..'>link</a>
基本上我有一个锚元素, <a href='bla..'>link</a>
On click, I first want to do something and only once it's done I want to take the user to the page that it links to. Something like:
单击时,我首先想做某事,只有在完成后我才想将用户带到它链接到的页面。就像是:
$('a').click(function(ev){
ev.preventDefault();
//do something here
ev.refireDefault();
});
Any suggestions?
有什么建议?
Update
更新
My apologies! My FireFox decided to cache the previous version of JS, so nothing that I tried worked until a simple CTRL+F5 solved the issue.
我很抱歉!我的 FireFox 决定缓存以前版本的 JS,所以在简单的 CTRL+F5 解决问题之前,我尝试过的一切都不起作用。
回答by Code Maverick
Javascript is not multi-threaded. It is event driven and events fire in the order in which you load them. Therefore, if you simply leave out the ev.preventDefault()
in your click event altogether, it won't fire the default action until the function exits.
Javascript 不是多线程的。它是事件驱动的,事件按加载顺序触发。因此,如果您ev.preventDefault()
在单击事件中完全省略 ,则在函数退出之前它不会触发默认操作。
EDIT per @Greg's comment:
根据@Greg 的评论编辑:
The only scenario in which the above is not true is with asynchronous functions. In that scenario you would want to prevent the default action first and then in the asynchronous callback function, re-fire the default action.
上面不正确的唯一场景是异步函数。在这种情况下,您可能希望先阻止默认操作,然后在异步回调函数中重新触发默认操作。
回答by Lazarus
preventDefault marks the event as handled so that when your click function exits, the default action isn't taken. If you don't call preventDefault then the default click action won't get called until your click function exits. So remove it and it'll work as you are suggesting.
preventDefault 将事件标记为已处理,以便当您的单击函数退出时,不会执行默认操作。如果您不调用 preventDefault ,则在您的 click 函数退出之前不会调用默认的点击操作。所以删除它,它会按照你的建议工作。
回答by Dustin Laine
The link will not go till after the work is done, so you can do:
该链接将在工作完成后才会出现,因此您可以执行以下操作:
$('a').click(function(ev){
//do something here
});
回答by Safran Ali
after performing your desired action why don't you just redirect it to the page by adding this line:
执行您想要的操作后,为什么不通过添加以下行将其重定向到页面:
window.location = 'welcome.php';
回答by Scherbius.com
It can be done like this:
可以这样做:
<a onclick="JavaScriptCodeHere; return true;" href='bla..'>link</a>
1) The onclickneeds to be beforethe href.
1) onclick需要在href之前。
2) return true;makes sure that user will be taken to the linked page after your JS code executes. If you use return false;
- linked itself will not work, it will just fire your JavaScript on click;
2)返回真;确保在您的 JS 代码执行后用户将被带到链接的页面。如果您使用return false;
-linked 本身将不起作用,它只会在点击时触发您的 JavaScript;