Javascript global variable is not updating

后端 未结 1 423
广开言路
广开言路 2021-01-24 17:13

I have this site that I am making. I want to update a global variable from another function. The global variable i is initialized to 0. I created 2 functions, 1 to

相关标签:
1条回答
  • 2021-01-24 18:07

    When you call the first function, you change the page content by loading a new page.

    Javascript variables aren't kept from one page to another one.

    So i is a new value after you called window.location.replace or window.location.href=.

    If you want to keep some values from one page to another one, you may use localStorage :

    var i = parseInt(localStorage['i'] || '0', 10); // loads the old saved value of i
    function verifyInput() {
        var u = login.username.value;
        var p = login.password.value;
        for (var c = 0; c <= 1; c++) {
            if (u === users[c] && p === password[c]) {
                i++;
                localStorage['i'] = i; // stores the incremented i
                alert(i);
                window.location.replace("login.htm"); // this ends the script and reload the page
                break; // this is useless : the script has ended
            } else {
                document.getElementById("username").value = "Invalid username...";
                window.location.href("home.htm"); // this is buggy
                break;
            }
        }
    }
    
    function logout() {
        alert(i);
        window.location.replace("home.htm");
    }
    

    Side note : window.location.href("home.htm"); wouldn't work : use window.location.href = "home.htm";

    0 讨论(0)
提交回复
热议问题