我一直在尝试为本地存储列表创建一个编辑页面,但是每当我尝试更改当前项时,它都会更改整个数组,而不仅仅是我更改的行。
HTML代码:
<div class="productform">
<h2>Edit Product Form</h2>
<form id="edit-form">
</form>
</div>
JS代码:
window.addEventListener('load', () => {
products = JSON.parse(localStorage.getItem('products')) || [];
const clickedId = localStorage.getItem('clickedId') || '';
const editForm = document.getElementById("edit-form");
products.forEach(product => {
if (clickedId == product.id) {
editForm.innerHTML = `
<input type="text" id="pName" class="form-control" value="${product.pName}" required>
<input type="text" id="pNumber" class="form-control" value="${product.pNumber}" required>
<input type="text" id="pColor" class="form-control" value="${product.pColor}" required>
<input type="number" id="plPrice" class="form-control" value="${product.plPrice}">
<button class="btn btn-success" type="submit">Save Changes</button>
<a href="index.html" class="btn btn-danger" >Go Back</a>
`;
}
});
products.forEach(product => {
editForm.addEventListener('submit', e => {
e.preventDefault();
const pName = editForm["pName"];
const pNumber = editForm["pNumber"];
const pColor = editForm["pColor"];
const plPrice = editForm["plPrice"];
const pName1 = pName.value;
const pNumber1 = pNumber.value;
const pColor1 = pColor.value;
const plPrice1 = plPrice.value;
const products = {
id: product.id,
pName: pName1,
pNumber: pNumber1,
pColor: pColor1,
plPrice: plPrice1,
done: product.done,
createdAt: product.createdAt
}
localStorage.setItem('products', JSON.stringify(products));
});
});
});
1条答案
按热度按时间of1yzvn41#
您将常量命名为
products
,同时循环遍历名为products
的数组。不覆盖
products
,而是追加product
数组(ID、名称、编号...)