0

这是jsfiddle:http: //jsfiddle.net/nng6L/7/

所以我想做的是以下几点:

  1. 我想在本地存储中设置一个值,1如果框被选中,或者0如果框未被选中
  2. 重新加载页面时,如果选中框,则保持选中状态,从 localstorage 获取值
  3. 我希望能够以纯文本形式显示 a1或 a 0,从 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">
4

2 回答 2

2

我删除了脚本中一些不必要的部分并稍微整理了一下,然后想出了这个......

// 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/

选中复选框并刷新页面以查看它是否有效。

于 2013-10-10T08:31:55.143 回答
0

您的代码中有几个语法错误,这就是它无法将值存储在 localStorage 中的原因。例如,这是一个:

onclick 中的相等运算符(== 而不是 =):

if(document.getElementById('xxxx').checked == true) {

要不就:

if(document.getElementById('xxxx').checked) {

另一个:

正如dystroy指出的那样,{在之前的额外悬空。else

现在它工作得很好:

见小提琴:http: //jsfiddle.net/nng6L/6/

你没有修复第二个!之前有一个额外的{悬垂else

于 2013-10-10T08:21:22.120 回答