运行函数然后点击链接 [英] Run function then follow link
问题描述
我似乎无法在这里找到我正在尝试做的事情的示例,但我确信这是可能的.
考虑以下事项:
当在 #main_nav
中的 link
被点击然后跟随 link
之前,我如何运行一个函数?
以下不起作用,因为在运行函数之前遵循链接.
$('#main_nav a').click(function() {//一些函数});
编辑
我实际上是在尝试在单击链接时使用 JQuery cookie 插件清除 cookie.我不确定这是否相关.
清除 cookie 代码是:
$.cookie('TMMenu', null);
TMMenu 是正确的名称,插件已加载.
编辑
对不起大家.问题实际上出在 JQuery Cookie 插件文档上.
$.cookie('TMMenu', null);
如自述文件中所述似乎不起作用.这样做:
$.cookie('TMMenu', null, { path: '/', expires: -5 });
更新:重新除了下面的 #1 之外,我看不出任何其他原因.>
我能想到这个问题的两个答案:
您在
#main_nav a
元素存在之前运行您的 jQuery 代码,并且没有连接任何事件处理程序.将您的脚本放在 HTML 文件的底部,就在结束</body>
标记之前,或使用ready
回调.您正在处理程序中执行异步操作,但没有看到它发生.这是因为一旦事件处理程序返回,链接就会被跟踪 —即使您的处理程序启动了一些异步操作.
以下是修复第二个的方法(两者都可以,如果您将其放在末尾或 ready
处理程序中):
$('#main_nav a').click(function(event) {//记住链接hrefvar href = this.href;//不要点击链接event.preventDefault();//做异步的事情startSomeAsyncThing(函数(){//这是异步事物的完成回调;//转到链接window.location = href;});});
I can't seem to find an example of what I'm trying to do here but I'm sure it's possible.
Consider the following:
<div id="main_nav">
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
<a href="/url/">LINK</a>
</div>
How can I run a function when a link
within #main_nav
is clicked before then following the link
?
The below doesn't work as the link is followed before the function is run.
$('#main_nav a').click(function() {
// Some Function
});
EDIT
I'm actually trying to clear a cookie with the JQuery cookie plugin when the links are clicked. I'm not sure if this is relevant or not.
The Clear cookie code is:
$.cookie('TMMenu', null);
TMMenu is the correct name and the plugin is loaded.
EDIT
Sorry everyone. The problem was actually with the JQuery Cookie plugin documentation.
$.cookie('TMMenu', null);
as described in the readme doesn't seem to work. This does:
$.cookie('TMMenu', null, { path: '/', expires: -5 });
Update: Re your edit: I can't see any reason that wouldn't work other than #1 below.
I can think of two answers to this question:
You're running your jQuery code before the
#main_nav a
element exists, and no event handler is hooked up. Put your script at the bottom of the HTML file, just before the closing</body>
tag, or use theready
callback.You're doing something asynchronous in your handler, and not seeing it happen. That's because as soon as the event handler returns, the link gets followed — even if your handler initiates some asynchronous action.
Here's how to fix the second one (both, if you put this at the end or inside a ready
handler):
$('#main_nav a').click(function(event) {
// Remember the link href
var href = this.href;
// Don't follow the link
event.preventDefault();
// Do the async thing
startSomeAsyncThing(function() {
// This is the completion callback for the asynchronous thing;
// go to the link
window.location = href;
});
});
这篇关于运行函数然后点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!