不附加和替换来自本地存储的数据

时间:2017-03-23 12:12:52

标签: javascript jquery json

对象被保存到localstorage中,我想要检索该对象并附加到页面,我也想在每次提交新表单时更改密钥名称,所以首先是key = key然后在下一个表单上提交我想要密钥= key1等。

但是我不知道如何实现这一点,有人可以帮助我吗?

var existingData = JSON.parse(localStorage.getItem("key")) || [];
$('body').append(existingData);
$('form').submit(function() {
var newArray = [];
    $(".add_id2").each(function(){
    newArray.push($(this).val());
});
var newArray2 = [];
    $(".add_id").each(function(){
    newArray2.push($(this).val());
});

var newData = {
  'title': $("#title").val(),
  'ingredients': $("#ingredients").val(),
  'instructions': $("#inst").val(),
  'moreingredients': newArray,
  'moreinstruction': newArray2,
  'img': img,
    };
existingData.push(newData);
localStorage.setItem("key", JSON.stringify(existingData));

1 个答案:

答案 0 :(得分:0)

您可以创建构造函数并使用new关键字调用它...请看一下。希望这会对你有所帮助。

示例: -

function formData(title, ingredients, instructions, moreingredients, img) {
    this.title = title;
    this.ingredients = ingredients;
    this.instructions = instructions;
    this.moreingredients = moreingredients;
    this.img = img;
}


var newData = new formData($("#title").val(), $("#ingredients").val(), $("#inst").val(), newArray, newArray2);