javascript - javaScript 问题 - setItem 正在覆盖 localstorage
问题描述
我的小组正在做的一个小学校项目有问题。
每当我将输入提交到 localstorage 时,它都会覆盖以前的 localStorage 项目。这个想法是稍后通过使用复选框等将成员输入与任务输入“合并”。
我希望能够从本地存储中列出许多名称和任务,但正如您所见,现在不可能,而且我有点卡住了
这是我的第一篇文章,给您带来的不便,我深表歉意,在此先感谢!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="css/testStyle.css" type="text/css" rel="stylesheet">
</head>
<body>
<h1>Arbeidskrav webprojekt</h1>
<fieldset>
<legend>Oppgavebeskrivelse</legend>
<input id="firstValue" type="text" placeholder="Oppgave">
<button id="firstBtn" type="button">Legg til oppgave</button>
</fieldset>
<fieldset>
<legend>Medlemsnavn</legend>
<input id="secondValue" type="text" placeholder="Medlemsnavn">
<button id="secondBtn" type="button">Legg til medlem</button>
</fieldset>
<fieldset>
<legend>Arbeidsoppgaver</legend>
<div id="taskOutput"></div>
</fieldset>
<fieldset>
<legend>Teammedlemmer</legend>
<div id="teamOutput"></div>
</fieldset>
<fieldset>
<legend>Fordelte arbeidsoppgaver</legend>
<div id="combinedOutput"></div>
</fieldset>
<script type="text/javascript">
const firstValue = document.getElementById("firstValue");
const secondValue = document.getElementById("secondValue");
const firstBtn = document.getElementById("firstBtn");
const secondBtn = document.getElementById("secondBtn");
const taskOutput = document.getElementById("taskOutput");
const teamOutput = document.getElementById("teamOutput");
const combinedOutput = document.getElementById("combinedOutput");
firstBtn.onclick = function(){
const keyOne = "task";
const valueOne = firstValue.value;
if(valueOne){
localStorage.setItem(keyOne, valueOne);
location.reload();
}else{
alert("Enter a valid task");
}
};
secondBtn.onclick = function(){
const keyTwo = "name";
const valueTwo = secondValue.value;
if(valueTwo){
localStorage.setItem(keyTwo, valueTwo);
location.reload();
}else{
alert("Enter a valid name");
}
};
for(let i = 0; i < localStorage.length; i++){
const key = localStorage.key(i);
const value = localStorage.getItem(key);
if(key == "task"){
taskOutput.innerHTML += `${value}<br>`;
}else{
teamOutput.innerHTML += `${value}<br>`;
}
}
</script>
</body>
</html>
解决方案
希望这对你有帮助。
而不是键,值(字符串),将值作为数组。
Ex: localStorage.setItem("key",["value1","value2"]);
console.log(localStorage);
length: 1
key: "value1,value2" (localStorage stores data in string format)
推荐阅读
- python - 标准化值,几乎达到最小值
- function - 如果在数据库中未找到每个输入的特定错误消息
- javascript - 如何将 scrollTop 设置为 div 容器的顶部?
- node.js - 我的 PeerJS 服务器返回一个 ID,但随后我收到 404 对“/peerjs”的后续请求
- operating-system - 无法在 Vmware Workstation 虚拟机中运行自定义操作系统 ISO
- flutter - WooCommerce 包,颤抖
- flutter - 带有 Rect.fromLTRB() 的 Canvas.drawRect() 不起作用
- javascript - Datalist 在 Angular 中动态填充对象,它不返回选定的对象值
- typescript - Typescript Project References 常见依赖参考
- html - Html表单不向服务器提交数据