0

我正在尝试获取键 1 的本地存储值,将其设置为选中的任何复选框的值,但我的 javascript 函数返回的值在本地存储中显示为 [object object]。任何帮助将不胜感激,在此先感谢您。

<html>

<head>

<script type="text/javascript">


function topic_1_status(){

var status = {
    get_value: function(){
         return this.value;
                    }

            };

localStorage.setItem(1, status);


}


</script>

</head>

<body>

<div>Topic no.1   </div>
<form action="">
<input type="checkbox" value="learnt" onclick="topic_1_status()" /> Learnt
<input type="checkbox" value="memorised" onclick="topic_1_status()" /> Memorised
<input type="checkbox" value="understood" onclick="topic_1_status()" /> Understood
<input type="checkbox" value="unlearned" onclick="topic_1_status()" /> Unlearned


</body>

</html>
4

2 回答 2

1

您正在获取“对象对象”,因为您存储的是对象“状态”而不是复选框的值。

这种修改应该会给你你想要的结果。

 **On the html where you call your javascript** 
 <input type="checkbox" value="learnt" onclick="topic_1_status(this);" />
 **As you can see above im passing 'this' to the function

和 javascript

 //On the javascript
 function topic_1_status(elem){
     if(!elem.checked){//You may also want to check that you are checking it rather than unchecking
        var checkboxValue = elem.value;
        localStorage.setItem(1,checkboxValue);
     }
 }

还想到提到似乎您想使用单选按钮而不是复选框,因为您计划一次只存储一个项目。

于 2012-09-01T18:37:25.860 回答
0

您的代码将值设置为状态。status 是一个复杂的对象。Local Storage 只能存储字符串。通常你会事先序列化成 JSON,但这并不是你真正想要的。我在想你只想做 localStorage.setItem(1, this.value); 请注意,尽管您绑定到 4 个不同的复选框并且始终写入一个值“1”。我不认为你想那样做。

于 2012-09-01T18:20:58.217 回答