首页 > 解决方案 > 如何在本地存储 (JS) HTML 按钮并在页面加载时检索按钮

问题描述

我想要一些关于我正在从事的项目的帮助。这个问题需要的部分是用户创建一个按钮,然后可以单击它以根据该按钮的 id(从用户输入创建)更新页面的某些部分。这行得通。

但是,我希望能够使用 localStorage 保存和检索这些按钮。我以前曾与 localStorage 合作过,但我尝试的任何方法似乎都不起作用。甚至可以在本地存储 HTML 元素吗?

只是寻找一些关于我应该如何去做的澄清,或者一个例子。

谢谢,艾略特。

在页面加载时:

if (typeof(Storage) !== "undefined") {
        let groupsLoaded = localStorage.getItem("storedGroupArray");
        $("#createdGroups").prepend(groupsLoaded);
}

创建和(希望)存储按钮时:

let groupArray = [];
      function addGroup() {
        let userInput = $("#groupName").val();
        if(userInput.length >= 1) {
          let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
          $("#createdGroups").append(newGroup);
          groupArray.unshift(newGroup);
          let groups = localStorage.setItem("storedGroupArray", userInput);
          $("#groupName").val("");
        } else {
          alert("Please enter a group name.")
        }
      };

到目前为止的代码链接:

https://codepen.io/elliot7-7/pen/zYvrBWy

(忽略任务部分)

标签: javascripthtmlbuttonlocal-storage

解决方案


我会将一组创建的组名存储在localStorage.

稍后可以将它们作为具有指定模板的 html 元素进行检索和处理。

let groupArray = [];
let groupNames = [];

function addGroup() {
  let userInput = $("#groupName").val();

  if(userInput.length >= 1) {
    let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
    $("#createdGroups").append(newGroup);
    groupArray.unshift(newGroup);

    groupNames = [...groupNames, userInput];
    localStorage.setItem("storedGroupArray", JSON.stringify(groupNames));

    $("#groupName").val("");

  } else {
    alert("Please enter a group name.")
  }
};
if (typeof(Storage) !== "undefined") {
  let storedGroupNames = JSON.parse(localStorage.getItem("storedGroupArray"));

  if(storedGroupNames) {
    for(let groupName of storedGroupNames) {
      let newGroup = $(`<button id='${groupName}' class='createdGroupsButton'>${groupName}</button>`);
      $("#createdGroups").append(newGroup);
    } 

  }

}

推荐阅读