我在 js 中创建了一个简单的文本框应用程序,在应用程序中,当我输入一个值时,它会暂时保存,但我想永久保存它。我使用了本地存储,但它不符合我的喜好。
这里是 JavaScript 部分
function addValue(){
let ad = document.getElementById("u");
let newli = document.createElement("li");
newli.textContent = document.getElementById("box3").value;
document.getElementById("box3").value = " ";
let local = ad.appendChild(newli);
localStorage.setItem('name',local.textContent);
}
这里是html部分
<ul id="u">
<li>task1 </li>
<li> task 2 </li>
<li> task 3</li>
</ul>
<input type="text" id= "box3">
<input type="button" value="add " onclick="addValue()">
答案 0 :(得分:3)
您需要将数据存储在数组中。
像这样保存 localStorage.setItem('name',local.textContent);
会覆盖内容,用新值替换它。
使用数组,您可以附加新内容而不是覆盖它。
使用此代码
var storage = localStorage.getItem("name");
if (storage) {
var storageContent = JSON.parse(localStorage.getItem("name"));
storageContent.push(newli.textContent);
localStorage.setItem("name", JSON.stringify(storageContent));
} else {
localStorage.setItem("name", JSON.stringify([newli.textContent]));
}
答案 1 :(得分:0)
关于您在评论中提出的问题。
首先我们要调用文档的Onload函数。 每当加载文档时都会调用此函数,因此是用于此项目的正确函数。
PS:我假设您熟悉箭头函数,这就是我使用它们的原因。让我知道它是否让您感到困惑
document.onload = (()=>{
// NB: IN ORDER FOR THIS CODE TO WORK MAKE SURE IT APPEARS AT THE BOTTOM OF THE HTML PAGE
// We get the elements from the localStorage and parse it into an array since it is a string at this stage
const items = JSON.parse(localStorage.getItem("name"))
// We select the parent element we want to append the items to
const parentUlToAppendTo = document.querySelector("#u")
// We use the map functions with template literals i.e (``) to return HTMLElements with the items as their innerHTML
const listItems = () => items.map(item => `<li>${item}</li>`)
// We Append The Elements To The parentUlToAppendTo Element
parentUlToAppendTo.insertAdjacentHTML("afterbegin",listItems())
})()
``