在 javascript onclick 功能完成之前链接重定向页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10712528/
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
Link redirects page before javascript onclick function is able to finish
提问by user1399694
I have a link that loads a page and calls a javascript function on click. Problem is the javascript function can't finish before the page redirects. Is there anyway to ensure it does ?
我有一个加载页面并在单击时调用 javascript 函数的链接。问题是 javascript 函数在页面重定向之前无法完成。有没有办法确保它确实如此?
You will notice there's an alert()
that is commented out in the javascript function, and if I uncomment it, the function is able to complete. However, I obviously don't want an alert popup to actually take place.
您会注意到alert()
在 javascript 函数中有一个被注释掉的,如果我取消注释它,该函数就可以完成。但是,我显然不希望实际发生警报弹出窗口。
Here is the link :
链接在这里 :
<a href="p.php?p=$randString&s=$postCat" onclick="setYSession();">
Here is the javascript function that can't finish in time :
这是无法及时完成的javascript函数:
function setYSession() {
var YposValue = window.pageYOffset;
$.get('yPosSession.php?yValue=' + YposValue);
//alert(YposValue);
return false;
}
回答by nnnnnn
Try changing the onclick
to return the result of your function:
尝试更改onclick
以返回函数的结果:
echo "<a href='p.php?p=$randString&s=$postCat' onclick='return setYSession();'>";
Or explicitly return false:
或者明确返回false:
echo "<a href='p.php?p=$randString&s=$postCat' onclick='setYSession();return false'>";
Given that your function returns false
, either way will stop the default event behaviour, i.e., it will stop the link navigating at all. Then within your function you can add code to do the navigation after your Ajax finishes:
鉴于您的函数返回false
,无论哪种方式都将停止默认事件行为,即,它将完全停止链接导航。然后在您的函数中,您可以添加代码以在 Ajax 完成后进行导航:
function setYSession() {
var YposValue = window.pageYOffset;
$.get('yPosSession.php?yValue=' + YposValue, function() {
window.location.href = 'p.php?p=$randString&s=$postCat';
});
return false;
}
Ideally, especially since you seem to be using jQuery for the $.get()
, I'd remove the inline onclick and do something like this:
理想情况下,尤其是因为您似乎在为 使用 jQuery $.get()
,我会删除内联 onclick 并执行以下操作:
echo "<a href='p.php?p=$randString&s=$postCat' id='myLink'>";
$("#myLink").click(function() {
var YposValue = window.pageYOffset,
myHref = this.href;
$.get('yPosSession.php?yValue=' + YposValue, function() {
window.location.href = myHref;
});
return false;
});
回答by Mario
<script>
function a()
{
setYSession();
window.location.href = "p.php?p=$randString&s=$postCat";
return false;
}
</script>
...
<a href='javascript: void(0);' onclick='a();'>click me</a>