从localStorage删除项目 [英] Remove an item from localStorage

查看:92
本文介绍了从localStorage删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在jQuery中创建一个简单的待办事项列表,但遇到了一个问题.这是我第一次尝试使用localStorage.因此,在为待办事项"列表建立结构之后,我想在刷新页面时查看自己的项目.所以首先我在JS中添加了这一行:

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());

然后我添加了

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

这部分工作正常,但我想在deleteListItem()函数的另一行上从存储中删除待办事项.这是我添加的行:

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());

添加此行后,我从浏览器中删除了整个<ul>元素.有没有办法扭转这种情况,也有办法使我的待办事项列表与localStorage一起正常工作.

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.

这里是我的JSBin,所以您可以更好地了解我在做什么:

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

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

推荐答案

您应该首先检查localStorage中是否已经存在某些东西:

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
}

检查此更新:
http://jsbin.com/damedomepi/1/edit?html,js,输出

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

这篇关于从localStorage删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆