我正在尝试在页面加载后检查它的地方存储boolean或int,这样我可以在页面加载后通过a
链接将布尔值更改为false。
我知道你可以将它作为隐藏文字或隐藏的单选按钮放在页面上,但这真的太丑了......
我还在考虑使用HTML 5的客户端存储。
到目前为止我有这个:
但是当我稍后在脚本中检查stopOnMouseOut它总是会返回true时,这显然不起作用......
stopOnMouseOut = true;
var stopSoundsVar = document.getElementById("stop_sounds");
stopSoundsVar.onclick = function() {
// toggle boolean
if (stopOnMouseOut == true) {
stopOnMouseOut = false;
}else {
stopOnMouseOut = true;
}
//alert(stopOnMouseOut);
return false;
}
这样做有什么最佳做法吗?
答案 0 :(得分:2)
正如您在问题中所述,您可以使用localStorage(持久性浏览器加载)或sessionStorage(仅持续页面生命周期 - 新窗口是新会话)。
使用localStrorage(或sessionStorage)非常简单:
localStorage.key = "value";
您只能在DOM存储中存储字符串,因此您可能需要将检索到的布尔值与"true"
或"false"
进行比较,而不仅仅是true
或false
。或者,您可以将数据转换为JSON,然后解析JSON。
使用localStorage保存数据:http://hacks.mozilla.org/2009/06/localstorage/
答案 1 :(得分:0)
您可以稍微简化一下条件:
var stopOnMouseOut = true,
stopSoundsVar = document.getElementById("stop_sounds");
stopSoundsVar.onclick = function() {
stopOnMouseOut = !stopOnMouseOut;
return false;
}