Javascript:使用更改的变量值重新加载页面

时间:2015-04-02 13:33:58

标签: javascript

是否可以在不修改页面源的情况下将变量“a”更改为“true”,以便打印“foo”?

<html>

 <head>
  <script>
   var a = false;
   if(a) document.write("foo");
   else document.write("bar");
  </script>
 </head>

 <body>
 </body>

</html>

我可以通过Chrome改变变量值。但如何重新加载才能看到“foo”,而不是“bar”

2 个答案:

答案 0 :(得分:0)

您可以在大多数现代浏览器上使用localstorage,请参阅http://www.w3schools.com/html/html5_webstorage.asp

如果您计划支持旧浏览器,则可以设置cookie,然后在文档重新加载时读取它。 http://www.w3schools.com/js/js_cookies.asp

编辑:试试这段代码

//function to check support for localStorage
function checkLocalStorageSupport() {
    try {
        localStorage.setItem("x", "x");
        localStorage.removeItem("x");
        return true;
    } catch (e) {
        return false;
    }
}
//function to read value of cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

if (checkLocalStorageSupport()) {
    if (localStorage.getItem('a') != null)
        if (localStorage.getItem('a') == "true")  //check that the value of localStorage is not null
            document.write("foo");                  //do operation if localStorage value is true
        else
            document.write("bar");
    else
        localStorage.setItem('a', 'false');
}
else {
    if (getCookie('a') != null)                     //check that the value of cookie is not null
        if (getCookie('a') == "true")
            document.write("foo");                  //do operation if cookie value is true
        else
            document.write("bar");
    else
        document.cookie = "a=false; expires=Thu, 31 Dec 2015 12:00:00 UTC"; //if no cookie exists set a cookie
}

答案 1 :(得分:0)

这应该如何运作?您无法使用静态HTML页面和嵌入式脚本在重新加载时保留状态。使用cookie或其他一些持久机制来存储状态。

相关问题