简体   繁体   English

如何检索存储在本地存储中的值?

[英]How to retrieve the value stored in localstorage?

var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
        $checkboxes = $("#list :checkbox");

    $checkboxes.on("change", function(){
        $checkboxes.each(function(){
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

I am using the code above to store the data into local storage. 我正在使用上面的代码将数据存储到本地存储中。

{"2":false,"3":false,"4":true}

The data stored in the local storage. 数据存储在本地存储中。 How can i get only the value 2 or false? 我怎样才能只得到值2或false? I want to collect the data in the local storage and stored into an array during submit the form. 我想在提交表单期间将数据存储在本地存储中并存储到数组中。

var items=[];
$.each(checkboxValues, function(key, value) {
            if(value===true){
                $("#" + key).prop('checked', value);
                items.push(key);
            }
        });

The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. 代码似乎在提交过程中出现问题,这在将数据存储到数据库时导致完整性约束重复条目。 I am using ajax to post the data to server and store the data. 我正在使用ajax将数据发布到服务器并存储数据。 Is there anything wrong with my code? 我的代码有什么问题吗?

Use the below code to access the checkboxValues object. 使用以下代码访问checkboxValues对象。 You need to parse it. 您需要解析它。

var obj = JSON.parse(localStorage.getItem("checkboxValues"));

To access "2", use obj["2"] . 要访问“ 2”,请使用obj["2"]

var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM