页面中有新闻文章列表。每次用户点击它时,它都会将新闻 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);
})
},
最佳答案
需要读取旧数据,转换为对象(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 数据是如何使用(读取)的,所以我真的不能说哪个对您来说是更好的选择
关于javascript - 单击时在对象数组中追加新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273645/