如何在本地存储 (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


德玛西亚99
浏览 49回答 1
1回答

慕田峪4524236

我将在 中存储创建的组名称的数组localStorage。稍后可以使用指定模板将它们作为 html 元素进行检索和处理。let groupArray = [];let groupNames = [];function addGroup() {&nbsp; let userInput = $("#groupName").val();&nbsp; if(userInput.length >= 1) {&nbsp; &nbsp; let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);&nbsp; &nbsp; $("#createdGroups").append(newGroup);&nbsp; &nbsp; groupArray.unshift(newGroup);&nbsp; &nbsp; groupNames = [...groupNames, userInput];&nbsp; &nbsp; localStorage.setItem("storedGroupArray", JSON.stringify(groupNames));&nbsp; &nbsp; $("#groupName").val("");&nbsp; } else {&nbsp; &nbsp; alert("Please enter a group name.")&nbsp; }};if (typeof(Storage) !== "undefined") {&nbsp; let storedGroupNames = JSON.parse(localStorage.getItem("storedGroupArray"));&nbsp; if(storedGroupNames) {&nbsp; &nbsp; for(let groupName of storedGroupNames) {&nbsp; &nbsp; &nbsp; let newGroup = $(`<button id='${groupName}' class='createdGroupsButton'>${groupName}</button>`);&nbsp; &nbsp; &nbsp; $("#createdGroups").append(newGroup);&nbsp; &nbsp; }&nbsp;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5