javascript - 切换按钮 JS 在 LocalStorage 中更改值
问题描述
我正在尝试在列表旁边创建一个收藏按钮,人们可以随时打开和关闭该按钮,并将值存储在本地存储中,以便在刷新时保存。我将如何创建一个按钮,单击该按钮将变为黄色并将本地存储更新为“收藏夹”:True,如果再次按下该按钮将返回默认值并将本地存储更新为“收藏夹”:False。谢谢
function favourite(element) {
var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));
if (allPlaces.favourite == true) {
allPlaces.favourite = false;
element.querySelector('ion-icon').setAttribute('name', 'star-outline');
} else {
allPlaces.favourite = true;
element.style.color = '#FFE234';
element.querySelector('ion-icon').setAttribute('name', 'star');
}
localStorage.setItem("allPlaces", JSON.stringify(allPlaces));
}
这些是本地存储 (LS) 中的对象
“title”:标题,
“description”:描述,
“category”:类别,
“favourite”:false
解决方案
这应该适合你
window.onload = function () {
const btn = document.getElementById("button");
const allPlaces = JSON.parse(localStorage.getItem("allPlaces"));
if (allPlaces && allPlaces.favourite) {
btn.style.color = "#FFE234";
} else {
btn.style.color = "#000000";
}
};
function favourite(element) {
var allPlaces = JSON.parse(localStorage.getItem("allPlaces")) || {};
if (allPlaces.favourite === true) {
allPlaces.favourite = false;
document.querySelector("ion-icon").setAttribute("name", "star-outline");
element.style.color = "#000000";
} else {
allPlaces.favourite = true;
element.style.color = "#FFE234";
document.querySelector("ion-icon").setAttribute("name", "star");
}
localStorage.setItem("allPlaces", JSON.stringify(allPlaces));
}
<button id='button' onclick="favourite(this)">Fav</button>
推荐阅读
- php - 如何解决这个错误 opencart Notice: Undefined property: Proxy::getTotalCustomersByTelephone in
- python - 在Django模板语言中的锚href内传递ID参数
- excel - 优化最佳外观选项打破了用户表单
- r - 保持毫秒转换时间戳
- regex - Spring Boot Regex 捕获所有路由
- java - 我可以像这样使用 .setMinimumFetchIntervalInSeconds(43200) 发布我的应用程序吗?
- android - 片段不显示整个回收站视图。它只显示一个卡片视图
- c# - 使用 LINQ 使用具有多重继承的对应子对象的组列表
- r - 创建一个循环以将遇到的数据下载并写入 csv
- gradle - 下面的 gradle 任务有什么问题?