admin管理员组文章数量:1254580
I'm trying to store multiple items based on this function:
onclick="s(iId)"
This is the function that I'm using:
function s(i_id) {
var items = [];
items.push(i_id);
localStorage.setItem("i", JSON.stringify(i));
}
The problem is that it is only storing one id when the button is clicked and refreshed every time is clicked. How can I make it store multiple ids?
I'm trying to store multiple items based on this function:
onclick="s(iId)"
This is the function that I'm using:
function s(i_id) {
var items = [];
items.push(i_id);
localStorage.setItem("i", JSON.stringify(i));
}
The problem is that it is only storing one id when the button is clicked and refreshed every time is clicked. How can I make it store multiple ids?
Share Improve this question edited May 27, 2016 at 12:15 Cherenkov asked May 27, 2016 at 12:06 CherenkovCherenkov 4951 gold badge8 silver badges16 bronze badges2 Answers
Reset to default 9The problem is, you're creating a new array, pushing a single id in it, and then saving it every time the function is called. Two things you could do is move the items
array outside of the function, and simply push to it, before saving them. The second option is, getting the already stored value, parsing it with JSON.parse
and pushing a new item in it, before saving it again.
I suggest going with option 1, even if it creates a global variable. It's much faster.
var items = [];
function store(item_id) {
items.push(item_id);
localStorage.setItem("item", JSON.stringify(items));
}
You have to call the onclick like this:
onclick="store([itemId1, itemId2, itemId3])"
and the function:
function store(item_ids) {
var items = [];
for(var i = 0; i < item_ids.length; i++) {
items.push(item_ids[i]);
}
localStorage.setItem("item", JSON.stringify(items));
}
Considering if you want to add new array to storage on every click...
本文标签: javascriptHow to store multiple items on Local Storage when a button is clickedStack Overflow
版权声明:本文标题:javascript - How to store multiple items on Local Storage when a button is clicked? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740809475a2289570.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论