javascript - 如何从本地存储 JavaScript 中删除同一键的多个值中的单个选定值
问题描述
从 JavaScript 本地存储中具有多个值的键中删除单个值。
$("ul").on("click", "li", function() {
$(this).remove();
localStorage.removeItem();
});
let itemsArray = localStorage.getItem('items')
? JSON.parse(localStorage.getItem('items'))
: [];
localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
解决方案
本地存储存储字符串。您的代码使用 JSON 来存储数组(作为字符串),这是一种常见且适当的方法。要从数组中仅删除一项,您:
- 从本地存储中获取 JSON
- 将 JSON 解析为数组
- 从数组中删除项目
- 获取更新后数组的 JSON
- 将其存储在本地存储中
通常我会在到达页面时执行第 1 步和第 2 步并保留结果。因此,我将对已有的结果执行第 3 步,然后将其放回存储中。你正在做类似的事情itemsArray
,所以类似于:
$("ul").on("click", "li", function() {
itemsArray = itemsArray.filter(entry => {
return /*...code to determine whether to keep `entry`, should
return true if `entry` isn't for this `li`, false if `entry`
IS for this `li` */;
});
$(this).remove();
localStorage.setItem("items", JSON.stringify(itemsArray));
});
推荐阅读
- ruby-on-rails - 如何在应用程序中制作自定义配置文件(它包括站点名称、徽标和 css 等变量),以便为不同的网站重用相同的代码库?
- android - 在 onMapReady 内部,Picasso 不会第一次加载图像,而是在重新创建活动后加载图像
- python - 在同步代码线程内具有回调的 Django 通道
- javascript - 如何通过套接字连接发送用户电子邮件地址?
- rust - 将值传递给参数之外的函数
- c# - 当事件处理程序代码在后台线程中执行?
- python - 如何修复一个遍历多个容器标签但只输出一个的刮板
- javascript - 从值数组中计算不同的 MongoDb
- javascript - 警告:`Reference` 不应在 CoreUI 仪表板中的`Manager` 组件之外使用
- neural-network - PyTorch - RuntimeError:后端 CPU 的预期对象,但参数 #2 'weight' 得到后端 CUDA