这是jsfiddle:http://jsfiddle.net/nng6L/7/
所以我想做的是:
- 我想在本地存储中设置一个值,如果选中该框,则为
1
;如果选中,则为0
复选框未选中 - 重新加载页面时,如果选中该框,则它会保持选中状态,并从本地存储中获取值
- 我希望能够以纯文本形式显示
1
或0
,已获取上述值来自本地存储。
这是我的代码,但它不起作用(重新加载页面时,未选中框;并且返回 null
而不是 1
或 0
):
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...
选中复选框并刷新页面以查看其工作情况。
关于javascript - 如何使用本地存储记住复选框是否已选中或未选中(单击时)并保存值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290371/