Link redirects page before javascript onclick func

2019-01-26 10:16发布

问题:

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 ?

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.

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 :

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

回答1:

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

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

Or explicitly return 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:

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:

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


回答2:

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