如何记住是否使用localstorage选中或取消选中(单击)框并保存值?
这是jsfiddle: http : //jsfiddle.net/nng6L/7/
所以我想做的是以下内容:
- 我想在localstorage中设置一个值,如果选中box则为
1
,如果未选中box,则为0
- 当重新加载页面时,如果选中了框,则它会保持选中状态,从localstorage中获取值
- 我希望能够以纯文本显示
1
或0
,从localstorage获取上述值。
这是我的代码,但它不起作用(重新加载页面时,不检查框;返回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中
Do you like summer?
我删除了一些不必要的脚本并稍微整理了一下并想出了这个……
// 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 ……
选中复选框并刷新页面以查看其是否有效。
您的代码中存在一些语法错误,这就是无法将值存储在localStorage中的原因。 例如,这里有一个:
onclick中的等于运算符(==而不是=):
if(document.getElementById('xxxx').checked == true) {
要不就:
if(document.getElementById('xxxx').checked) {
另一个:
额外的悬空{
在else
之前,如破坏所指出的那样。
现在工作得很好:
见小提琴: http : //jsfiddle.net/nng6L/6/
你没有修复第二个! 还有一个额外的{
悬挂在else
面前。