我有 4 个 html 页面,第 1-4 页。全局变量存储在 js 文件中,我想通过在每个网页上单击是/否来更新变量。 有没有办法保留变量?例如存储在网页浏览器还是硬盘中?
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/counter.js"></script>
</head>
<body>
<h1>Are u in?</h1>
<!--img tag-->
<div id="yes">
<input type="button" name="yes" value="Yes">
</div>
<div id="no">
<input type="button" name="yes" value="No">
</div>
<script type = "text/javascript">
$("#yes").click(function() {
count = 1; //page2 will getC() and count += 2 and setC(count)
setC(count);
window.location.replace("page2.html");//maybe this will clear out something
});
$("#no").click(function() {
window.location.replace("page2.html");
});
</script>
</body>
------------js文件------------------
var count;
function setC(c){
count = c;
}
function getC(){
return count;
}
最佳答案
您应该使用 cookie
跨请求存储值。您可以使用这个 jQuery 插件,使使用 cookie 变得非常容易:https://github.com/carhartl/jquery-cookie
这是一个简单的例子:
设置值
function setC(c){
$.cookie('the_count', c); //Cookie Key and Cookie Value
}
获取值
function getC(){
return $.cookie('the_count') || 0; //Pass in the cookie key
}
现在不需要全局变量计数。您只需使用 setC
和 getC
即可。如果您对稍微复杂的解决方案感兴趣,可以使用 AmplifyJS 而不是 jQuery cookie 插件。 AmplifyJS 将在可用时使用 HTML5 本地存储
,如果浏览器不支持本地存储,则回退到 cookie。更多信息请点击:http://amplifyjs.com/api/store/
关于javascript - 通过多个文件更新同一变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711910/