javascript - 如何使用本地存储记住复选框是否已选中或未选中(单击时)并保存值?

标签 javascript jquery html checkbox local-storage

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

所以我想做的是:

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

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

script.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;
            }
        }

output.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);

page.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/

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

关于javascript - 如何使用本地存储记住复选框是否已选中或未选中(单击时)并保存值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290371/

相关文章:

javascript - 谷歌图表加载消息

JavaScript 性别验证

javascript - 如何使用拉格朗日插值计算多项式的系数

jQuery 循环遍历表格单元格

javascript - 如何动态更改图像?

javascript - 如何使我的编号比例响应滚动和点击?

javascript - 制作一个不带eval()的动态变量对应一个数组

javascript - IE9 和 $(document).ready 失败,除非开发者控制台打开

javascript - onchange 函数在初始文本框中工作,但在另一个文本框中不起作用

javascript - 在 d3 堆叠条形图上使用 d3-tip 和 CSS 悬停效果