为了账号安全,请及时绑定邮箱和手机立即绑定

如何在本地存储 (JS) HTML 按钮并在页面加载时检索按钮

如何在本地存储 (JS) HTML 按钮并在页面加载时检索按钮

德玛西亚99 2023-12-25 16:01:34
我需要一些关于我正在从事的项目的帮助。此问题所需的部分是用户创建一个按钮,然后单击它以根据该按钮的 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
查看完整描述

1 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

我将在 中存储创建的组名称的数组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);

    } 


  }


}


查看完整回答
反对 回复 2023-12-25
  • 1 回答
  • 0 关注
  • 43 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信