单击时在 object 数组中追加新数据

Append new data in object array on click

页面中有新闻文章列表。每次用户点击它时,它都会将新闻 ID 和标题保存到本地存储。每次单击新项目时,我的代码都会替换本地存储数据。

如何将新数据追加到 localStorage 中?

正在设置本地存储

awardForArticleRead: function(latestNews){
    var articleData = {};
    articleData['newsId'] = latestNews.news_id;
    articleData['newsTitle'] = latestNews.title;
    localStorage.setItem("articleRead",  JSON.stringify(articleData));
},

进入详情页面时调用函数

    newsDetail: function(key, id) {
    var _this=this;

    newsDetail = API_DATA['getLatestNews'][key];

    myApp.mainView.loadPage('news1.html');
    myApp.onPageInit("news_detail", function(page){
        _this.awardForArticleRead(newsDetail);
        _this.showNewsDetails(newsDetail);
    })       

},

没有设置添加或追加功能,但是您可以简单地收集旧数据,在代码中组合它们并将新数据替换到本地存储中。

像这样:

function addToLocalStorage(nameOfItem, newData){
    var oldData = localStorage.getItem(nameOfItem);
    if(oldData !== null) {
        localStorage.setItem(nameOfItem, oldData + newData);
    } else {
        localStorage.setItem(nameOfItem, newData);
    }
}

需要读取旧数据,转换为对象(JSON.parse),添加新数据,然后将修改后的数据写入localStorage

awardForArticleRead: function(latestNews){
    var store = JSON.parse(localStorage.getItem("articleRead") || '[]');
    store.push({
        newsId: latestNews.news_id,
        newsTitle: latestNews.title
    });
    localStorage.setItem("articleRead",  JSON.stringify(store));
},

这将生成一个项目数组,例如:

[{
    newsId: 1,
    newsTitle: 'title 1'
}, {
    newsId: 2,
    newsTitle: 'title 2'
}, {
    newsId: 3,
    newsTitle: 'title 3'
}]

因此读取 localStorage 的其他代码必须适当更改

或者:

awardForArticleRead: function(latestNews){
    var store = JSON.parse(localStorage.getItem("articleRead") || '{}');
    store[latestNews.news_id] = latestNews.title;
    localStorage.setItem("articleRead",  JSON.stringify(store));
}

将导致数据为:

{ 
    1: 'title1',
    2: 'title2',
    3: 'title3',
}

其中 1、2、3 是 news_id 的

由于您没有展示 localStorage 数据是如何使用(读取)的,所以我真的不能说哪个更适合您