首页 > 解决方案 > 切换按钮 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

标签: javascript

解决方案


这应该适合你

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>

推荐阅读