如何记住是否被选中或取消选中(点击)与localstorage,还保存一个值? [英] How to remember whether box is checked or unchecked (on click) with localstorage and also save a value?
本文介绍了如何记住是否被选中或取消选中(点击)与localstorage,还保存一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想做的是:
- 我想在localstorage中设置
1
如果选中框,或0 $>
- 当页面重新加载时,如果选中了框,则它保持选中状态,并从localstorage中获取值
$ b $ b - 我想要显示
1
或
- I want to set a value in localstorage, of
1
if box is checked, or0
if box is unchecked - When page is reloaded, if box was checked then it stays checked, having fetched the value from localstorage
- I want to be able to display either a
1
or a0
in plain text, having fetched the aforementioned value from localstorage.
这是我的代码,但是它不工作(当页面重新加载时,框未选中;并返回 null
,而不是 1
或 0
):
Here is my code, but it is not working (when page is reloaded, box is not checked; and null
is returned instead of a 1
or a 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 / p>
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">
推荐答案
我删除了一些不必要的脚本,有一点,想出了这个...
I removed some unnecessary bits of the script and tidied it a little and came up with this...
// 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 ...
Here's a working jsFiddle...
选中复选框并刷新页面以使其正常工作。
Check the checkbox and refresh the page to see it work.
这篇关于如何记住是否被选中或取消选中(点击)与localstorage,还保存一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文