Remove an item from localStorage

扶醉桌前 提交于 2019-12-20 04:16:09

问题


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



来源:https://stackoverflow.com/questions/40966232/remove-an-item-from-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!