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 badges
Add a ment  | 

2 Answers 2

Reset to default 9

The 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