简体   繁体   中英

Javascript not redirecting page

I have the following html code:

<html>
    <head>
        <script type="text/javascript" src="buttonClicked.js"></script>
    </head>
    <body>
        <form id="confirmChangeId" name="selectionForm" method="POST">
            <input id="btnChange" type="submit" value="Change">
        </form>
    </body>
</html>

using the following javascript:

window.onload = function() {
    initFunc();
}

var initFunc = function() {
    var change = document.getElementById("btnChange");
    change.onclick=function() {
        window.location.href='http://stackoverflow.com';
        //alert("change button clicked"); // If this line is uncommented, then the page re-direction does occur
    }
}

Using Firefox, when the alert is uncommented in the JS file then the redirection does occur. To throw a further spanner in the works, no redirection occurs whatsoever when using Chrome or Opera. I'm clearly missing something small here, but can't find what it is. Suggestions?

If you want the redirection to reliably work, you must add return false; at the end of your onlick function.

Note: You should really attach event listeners to the objects instead of using the outdated onclick property.

var change = document.getElementById("btnChange");
change.addEventListener('click', function(event) {
    event.preventDefault(); // stops the click from completing
    window.location.href='http://stackoverflow.com';
}, false);

Add return false; in your function.otherwaise form being submited before redirect

 var initFunc = function() {
 var change = document.getElementById("btnChange");
 change.onclick=function() {
    window.location.href='http://stackoverflow.com';
    return false;
    //alert("change button clicked"); // If this line is uncommented, then the page re-         direction does occur
  }
 }

The code below should work. It is imperative that you add the return false to your onlcik function. You need event listeners.

See below:

<script>
window.onload = function() {
    initFunc();
}

var initFunc = function() {
    var change = document.getElementById("btnChange");
change.addEventListener('click', function(event) {
    event.preventDefault(); // stops the click from completing
    window.location.href='http://stackoverflow.com';
}, false);
}
</script>

<html>
    <head>

    </head>
    <body>
        <form id="confirmChangeId" name="selectionForm" method="POST">
            <input id="btnChange" type="submit" value="Change">
        </form>
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM