Remove an item from localStorage

2019-02-27 22:36发布

问题:

I'm trying to make, a simple To-Do list in jQuery and I've ran into a problem. This is my first time trying to use localStorage. So after making structure for my To-Do list, I wanted to see my items when I refresh page. So first I added this line in my JS:

localStorage.setItem("todolist", $('#todoList').html());

Then I added

$('#todoList').html(localStorage.getItem("todolist"));

And this part was working fine but I wanted to another line on my deleteListItem() function for deleting my To-Do items from storage. This was the line I added:

localStorage.removeItem("todolist", $('#todoList').html());

After adding this line I deleted my whole <ul> element from browser. Is there a way to reverse this also is there a way to make my To-Do list to work properly with localStorage.

Here is mine JSBin so you better understand what I'm doing:

http://jsbin.com/ciyufi/2/edit?html,js,output

回答1:

You should first check if something already exists in the localStorage:

if (localStorage.getItem("todolist") != null) {
    $('#todoList').html(localStorage.getItem("todolist")); // This reads items in our local storage
}

Check this update:
http://jsbin.com/damedomepi/1/edit?html,js,output