gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:16:02 27 4
gpt4 key购买 nike

这是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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com