存储一个布尔值或整型值,并在页面加载后检查/更改它的值

Storing a boolean or int and check/change it's value after the page has loaded

本文关键字:加载 检查 一个 布尔值 整型 存储      更新时间:2023-09-26

我试图存储一个布尔值或int在页面加载后我可以检查它的地方,这样我就可以在页面加载后将布尔值更改为false(通过a链接)。

我知道你可以把它作为隐藏文本或隐藏单选按钮放在页面上,但那真的很难看…

我也在考虑使用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;
     }

有什么最好的做法吗?

正如您在问题中所述,您可以使用localStorage(在浏览器加载时持久)或sessionStorage(仅持续页面的生命周期-新窗口是新会话)。

使用localstorage(或sessionStorage)很容易:

localStorage.key = "value";

您只能将字符串存储在DOM存储中,因此您可能必须将检索回来的布尔值比较为"true""false",而不仅仅是truefalse。或者,您可以将数据转换为JSON,然后将JSON解析出来。

使用localStorage保存数据:http://hacks.mozilla.org/2009/06/localstorage/

兼容性:http://dev-test.nemikor.com/web-storage/support-test/

您可以稍微简化一下条件:

var stopOnMouseOut = true,
    stopSoundsVar = document.getElementById("stop_sounds");
stopSoundsVar.onclick = function() {
    stopOnMouseOut = !stopOnMouseOut;
    return false;
 }

演示:http://jsfiddle.net/bHmyj/