这是jsfiddle:http: //jsfiddle.net/nng6L/7/
所以我想做的是以下几点:
- 我想在本地存储中设置一个值,
1
如果框被选中,或者0
如果框未被选中 - 重新加载页面时,如果选中框,则保持选中状态,从 localstorage 获取值
- 我希望能够以纯文本形式显示 a
1
或 a0
,从 localstorage 获取上述值。
这是我的代码,但它不起作用(重新加载页面时,未选中框;并且null
返回而不是 a1
或 a 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);
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">