我成功创建了一个jquery对象,然后使用以下代码将对象作为json字符串保存到本地存储变量中,该代码循环遍历列表并将项添加到myObject变量,然后将对象保存到本地存储变量。
var x =$("[name=checklist]").length;
var myObject = {};
myObject.Vehicle_Check = [x];
$("[name=checklist]").each(function(index){
if (index >0) {
myObject.Vehicle_Check.push({});
var PT = $("[name=problemtxt_" + index + "]").val(); //the fault label
var CL = $("[name=checklbl_" + index + "]").text(); //the question
var d = $("[name=optiongroup_" + index + "]:checked").val();
if (d == 'Item 1') {
d='OK'
}
else if (d == 'Item 2') {
d='Fault'
localStorage.setItem('fault', 1);
}
myObject.Vehicle_Check[index].question = CL;
myObject.Vehicle_Check[index].result = d;
myObject.Vehicle_Check[index].Fault = PT;
}
});
localStorage.setItem('results' ,JSON.stringify(myObject));
我试图通过一次构造一个项目将其保存到本地存储变量来做同样的事情然后当我希望添加另一个项目时使用parseJSON从变量中检索对象并添加一个附加项目然后保存回到变量。我没有正常工作。我该如何正确地构建它?
Initiate the object:
var myObject = {};
myObject.Vehicle_Check = [18];
myObject.Vehicle_Check.push({});
localStorage.setItem('checkobject',JSON.stringify(myObject));
Add to the object:
var myObject = jQuery.parseJSON(localStorage.getItem('checkobject'));
myObject.Vehicle_Check.push({});
myObject.Vehicle_Check[I].question = 'First test!';
myObject.Vehicle_Check[I].result = 'OK';
myObject.Vehicle_Check[I].Fault = 'none';
localStorage.setItem('checkobject',JSON.stringify(myObject))
答案 0 :(得分:1)
您尚未定义I
。你可能会做这样的事情,所以你不必担心索引:
var myObject = {};
myObject.Vehicle_Check = [];
localStorage.setItem('checkobject', JSON.stringify(myObject));
...
var myObject = jQuery.parseJSON(localStorage.getItem('checkobject'));
var next = {
question: 'First test!',
result: 'OK',
Fault: 'none'
};
myObject.Vehicle_Check.push(next);
localStorage.setItem('checkobject', JSON.stringify(myObject));
编辑 - 根据您的使用情况,这可以进一步简化:
myObject.Vehicle_Check.push({
question: 'First test!',
result: 'OK',
Fault: 'none'
});