我正在使用localStorage存储一些值,但对我确认为字符串的输入不起作用。它适用于“鸡”之类的硬编码字符串,但不适用于input.value,这是我的代码:https://codepen.io/levinson2504/pen/gObzZON?editors=0011
let menu = [];
const menuDiv = document.querySelector("#menu");
const inputName = document.querySelector("#item-name");
const inputPrice = document.querySelector("#item-price");
document.querySelector("#add-btn").addEventListener("click", addItem);
document.querySelector("#del-btn").addEventListener("click", () => delItem(menu.length - 1));
function render(items) {
menuDiv.innerHTML = "";
[inputName, inputPrice].forEach(input => input.value = "");
items.forEach((item, index) => menuDiv.append(menuElement(item, index)));
}
function menuElement(item, index) {
const menuText = document.createElement("span");
menuText.innerText = `${item.itemName} - ${item.itemPrice}`;
const delBtn = document.createElement("button");
delBtn.innerText = "delete item";
delBtn.addEventListener("click", () => delItem(index));
const itemDiv = document.createElement("div");
[menuText, delBtn].forEach(el => itemDiv.append(el));
return itemDiv;
}
function delItem(index) {
menu.splice(index, 1);
render(menu);
}
function addItem() {
menu.push({
itemName: inputName.value,
itemPrice: inputPrice.value
});
render(menu);
let item = "chicken"
localStorage.setItem("itemName", item);
localStorage.setItem("itemPrice", inputPrice.value );
console.log(localStorage.getItem("itemName"));
console.log(localStorage.getItem("itemPrice"));
}
最佳答案
您的render
方法清除您的输入值。由于在设置localStorage中的值之前要先调用render
,因此您只会得到一个空值。在调用render
之前将值存储在localStorage中:
function addItem() {
menu.push({
itemName: inputName.value,
itemPrice: inputPrice.value
});
let item = "chicken"
localStorage.setItem("itemName", item);
localStorage.setItem("itemPrice", inputPrice.value);
console.log(localStorage.getItem("itemName"));
console.log(localStorage.getItem("itemPrice"));
render(menu);
}
关于javascript - localStorage第二个参数不接受input.value,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59925703/