javascript 如何使用js将已编辑的行推送到本地存储中

h5qlskok  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(128)

我一直在尝试为本地存储列表创建一个编辑页面,但是每当我尝试更改当前项时,它都会更改整个数组,而不仅仅是我更改的行。
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));
        });
    });
});
of1yzvn4

of1yzvn41#

您将常量命名为products,同时循环遍历名为products的数组。
不覆盖products,而是追加product数组(ID、名称、编号...)

var newProduct = {
    id: product.id,
    pName: pName1,
    pNumber: pNumber1,
    pColor: pColor1,
    plPrice: plPrice1,
    done: product.done,
    createdAt: product.createdAt
}

// create a new array so we do not modify the original array we are currently looping into
var updatedProducts = products.slice();
updatedProducts.push( newProduct );

localStorage.setItem('products', JSON.stringify(updatedProducts ));

相关问题