如何记住复选框是选中还是取消选中(单击时)使用本地存储并保存值

How to remember whether box is checked or unchecked (on click) with localstorage and also save a value?

本文关键字:存储 保存 单击 复选框 何记住 取消      更新时间:2023-09-26

这是jsfiddle:http://jsfiddle.net/nng6L/7/

所以我想做的是:

  1. 我想在本地存储中设置一个值,如果选中框,则1,如果未选中框,则0
  2. 当页面重新加载时,如果选中了框,则它保持选中状态,从本地存储获取值
  3. 我希望能够以纯文本形式显示10,从本地存储中获取上述值。

这是我的代码,但它不起作用(重新加载页面时,未选中框;并且返回null而不是10(:

脚本.js

    // here is to set item in localstorage when you click the check box.
    vvvvvvv = document.getElementById('xxxx');      
    vvvvvvv.onclick = function() {
        if(document.getElementById('xxxx').checked=true) {
            localStorage.setItem('yyyyyyy', "1");
        } else {
            localStorage.setItem('yyyyyyy', "0");
        }
    }
    // here is to fetch the item stored in local storage, and use that value
    // to check or uncheck the box based on localstorage value.
    zzzzzzz = localStorage.getItem('yyyyyyy');
    if (zzzzzzz === null) {
            localStorage.setItem('yyyyyyy', "0");
            document.getElementById("xxxx").checked=false;
        }
        else {
            if (zzzzzzz === "1") {
                document.getElementById("xxxx").checked=true;
            } else if (zzzzzzz === "0") {
                document.getElementById("xxxx").checked=false;
            }
        }

输出.js

    // here is to output the value to the web page so we can know 
    // what value is stored in localstorage.
    wwwwwwww = localStorage.getItem('yyyyyyy');
    document.write(wwwwwwww);

页.html

<!-- here is the check box for which the scripts above are based from -->
<input type="checkbox" id="xxxx">Do you like summer?
<br><br>
<!-- here is where it will display the value from localstorage -->
<script src="output.js">

我删除了一些不必要的脚本并对其进行了一点整理,然后想出了这个......

// here is to set item in localstorage when you click the check box.
vvvvvvv = document.getElementById('xxxx');      
vvvvvvv.onclick = function() {
    if(document.getElementById('xxxx').checked) {
        localStorage.setItem('yyyyyyy', "1");
    } else {
        localStorage.setItem('yyyyyyy', "0");
    }
}
// here is to fetch the item stored in local storage, and use that value
// to check or uncheck the box based on localstorage value.
zzzzzzz = localStorage.getItem('yyyyyyy');
console.log(zzzzzzz);
if (zzzzzzz === "1") {
    document.getElementById("xxxx").checked=true;
} else {
    document.getElementById("xxxx").checked=false;
}

这是一个有效的jsFiddle...

http://jsfiddle.net/nng6L/5/

选中复选框并刷新页面以查看其工作情况。

代码中有几个语法错误,这就是它无法将值存储在 localStorage 中的原因。例如,这里有一个:

点击中的相等运算符(== 而不是 =(:

if(document.getElementById('xxxx').checked == true) {

或只是:

if(document.getElementById('xxxx').checked) {

另一个:

正如dystroy指出的那样,在else之前额外悬空{

现在它工作得很好:

见小提琴:http://jsfiddle.net/nng6L/6/

你没有修复第二个!else前还有一个额外的{晃来晃去。