亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在本地存儲 (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 關注
  • 145 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號