如何记住复选框是选中还是取消选中(单击时)使用本地存储并保存值
How to remember whether box is checked or unchecked (on click) with localstorage and also save a value?
这是jsfiddle:http://jsfiddle.net/nng6L/7/
所以我想做的是:
- 我想在本地存储中设置一个值,如果选中框,则
1
,如果未选中框,则0
- 当页面重新加载时,如果选中了框,则它保持选中状态,从本地存储获取值
- 我希望能够以纯文本形式显示
1
或0
,从本地存储中获取上述值。
这是我的代码,但它不起作用(重新加载页面时,未选中框;并且返回null
而不是1
或0
(:
脚本.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
前还有一个额外的{
晃来晃去。
相关文章:
- 如何在本地存储(或其他数据库)上安全地保存敏感访问代码
- JavaScript-保存、存储和更新数组
- 在本地存储中保存并返回随机生成的字符串
- 如何保存和存储实时流中的音频
- 本地存储保存和检索文本输入值
- 表单选择不保存在本地存储中
- Javascript 会话存储变量未正确保存
- 没有从本地存储获取与保存的变量相同的类型
- 无法使用HTML5 Web存储保存布尔值的解决方法
- 使用 HTML5 本地存储保存多个值
- 使用本地存储保存和加载输入值
- 使用 jQuery cookie 或本地存储保存 .addClass
- 尝试用javascript创建一个座位预订系统,并用本地存储保存数据
- 从本地存储保存特定数据
- 使用HTML5本地存储保存视图状态
- 如何使用 HTML5 本地存储保存表单中的数据
- HTML5本地存储保存笔记
- jquery,Html5文本框从本地存储保存/加载
- 会话存储:保存的对象数量
- 本地存储保存表单N页数据,直到最后提交