繁体   English   中英

localstorage 删除了以前的数据,如何添加新数据?

[英]localstorage deletes the previous data, how can I add new data?

我在哪里犯了错误? 当我添加新数据时,它会删除以前的数据并添加新数据。 但是,我希望它是这样的; 如果有id,不要添加,否则新数据会和之前的数据一起添加。

let array_item = [];

$('#bookmark').click(function() {

    let id = $(this).data("id");
    // We place the data from data-id into the array item array.

    array_item.push(id);

    let parsed = JSON.stringify(array_item);
    localStorage.setItem('array_item', parsed);
    console.log(parsed);
})

预先感谢您对我们的支持

您需要检索存储中的数据,添加到其中,然后保存结果。 如果您不需要处理程序之外的array_item ,则如下所示:

$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
    array_item.push(id);
    localStorage.setItem("array_item", JSON.stringify(array_item));
});

如果您确实需要在处理程序之外使用它,但处理程序是您添加到它的唯一位置,则如下所示:

const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    array_item.push(id);
    localStorage.setItem("array_item", JSON.stringify(array_item));
});

或者你可以有一个可以从多个地方调用的函数:

const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
function addArrayItem(item) {
    array_item.push(item);
    localStorage.setItem("array_item", JSON.stringify(array_item));
}
$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    addArrayitem(id);
});

暂无
暂无

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

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