javascript - 如何在本地存储 (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
(忽略任务部分)
解决方案
我会将一组创建的组名存储在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);
}
}
}
推荐阅读
- prolog - 如何从 pwsip 导入 Prolog
- wpf - 从另一个线程绑定和更新
- javascript - 'v-bind' 指令需要一个属性值 - 带有动态数据
- upload - s3cmd - 删除失败的分段上传占用空间并收费
- javascript - Crud MEAN Dron 地理定位
- node.js - Node.js flash 任务栏图标?
- python-behave - 在 PyBehave 中使用示例时,您可以在一个步骤中将它们输入到表格中吗?
- c++ - 链接器在包含目录中找不到实现
- django - django中数据库存储vlaues中的IntegrityError?
- python - 在 AWS Elasticbeanstalk 中执行 python 入口点命令时如何包含命令?