在javascript onclick函数能够完成之前链接重定向页面 [英] Link redirects page before javascript onclick function is able to finish

查看:111
本文介绍了在javascript onclick函数能够完成之前链接重定向页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接加载一个页面,并在点击时调用一个javascript函数。问题是JavaScript功能在页面重定向之前无法完成。是否有,以确保它?

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函数,如果我取消注释它,该函数就能够完成。然而,我显然不希望有一个提醒弹出窗口。

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.

以下是链接:

<a href="p.php?p=$randString&s=$postCat" onclick="setYSession();">

以下是无法及时完成的​​javascript功能:

Here is the javascript function that can't finish in time :

function setYSession() {
    var YposValue = window.pageYOffset;
    $.get('yPosSession.php?yValue=' + YposValue);
    //alert(YposValue);
    return false;
}


推荐答案

尝试更改 $ onclick 返回你的函数的结果:

Try changing the onclick to return the result of your function:

echo "<a href='p.php?p=$randString&s=$postCat' onclick='return setYSession();'>";

或明确返回false:

Or explicitly return false:

echo "<a href='p.php?p=$randString&s=$postCat' onclick='setYSession();return false'>";

假设函数返回 false ,方式将停止默认的事件行为,即,它将完全停止链接导航。然后在您的函数中,您可以添加代码以在Ajax完成后执行导航:

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:

function setYSession() {    
    var YposValue = window.pageYOffset;
    $.get('yPosSession.php?yValue=' + YposValue, function() {
       window.location.href = 'p.php?p=$randString&s=$postCat';
    });

    return false;    
}

理想情况下,特别是因为您似乎在使用jQuery for $。get(),我会删除内联onclick并执行如下操作:

Ideally, especially since you seem to be using jQuery for the $.get(), I'd remove the inline onclick and do something like this:

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;
});

这篇关于在javascript onclick函数能够完成之前链接重定向页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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