2015-04-02 78 views
1

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

<html> 

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

<body> 
</body> 

</html> 

我可以从Chrome中随意更改变量值。但如何重装看“富”,而不是“酒吧”

+1

无需修改源代码?没有。通过修改脚本,使其从'localStorage','sessionStorage',cookies,AJAX读取状态值,或者使用由服务器端语言提供的值?是。 – zzzzBov 2015-04-02 13:40:14

回答

0

可以在大多数现代浏览器中看到http://www.w3schools.com/html/html5_webstorage.asp

,如果你打算支持旧的浏览器,你可以设置一个cookie,然后当读它使用localStorage的文件重新加载。 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

这些只是指向潜在答案的链接;请张贴一些相关的代码,因为链接可能随时间而改变,使得这个答案无关紧要。 – rfornal 2015-04-02 13:51:36

+0

编辑以发布代码。感谢rfornal – 2015-04-04 09:38:24

0

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