You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript CRUD应用localStorage存储数据表格显示错位问题求助

问题原因

你遇到的列不匹配问题核心由3个错误导致:

  • 提交表单时,你先把FormData转成对象推入数组存localStorage,之后才给隐藏字段no赋值,导致存在localStorage里的每条记录没有有效no值,刷新渲染时数据对应逻辑出错
  • 删除数据逻辑完全错误:拿DOM节点的textContent和存储的对象直接对比,永远不会成立,无法正确删除localStorage里的对应数据
  • 删除数据时localStorage.setItem第一个参数误写为数组dataArr,导致存储键名异常,旧数据读取混乱

修复后的完整JS代码

const 
  myForm       = document.forms['my-form'],
  table        = document.querySelector('#myTable tbody'),
  dataArr       = JSON.parse(localStorage.getItem('dataArr') || '[]');

var selectedRow = null
// 初始化序号从存储数据的长度开始,避免重复
var number = dataArr.length

// 表格初始化渲染
dataArr.forEach(row=>{
    let newRow = table.insertRow()
    newRow.insertCell().textContent = row.no
    newRow.insertCell().textContent = row.inputNL
    newRow.insertCell().textContent = row.inputJK
    newRow.insertCell().textContent = row.inputNH
    newRow.insertCell().textContent = row.inputA 
    newRow.insertCell().innerHTML = `<a onClick="onDelete(this)"><i class="fas fa-times"></i></a>`
})

function onFormSubmit() {
    if (validate()) {
        if (selectedRow == null) {
            // 先给no字段赋值再读取表单数据
            const curNo = ++number
            myForm.no.value = curNo
            const formData = Object.fromEntries(new FormData(myForm).entries())
            dataArr.push(formData)
            localStorage.setItem('dataArr', JSON.stringify( dataArr ))
            
            // 插入新行
            let newRow = table.insertRow()
            newRow.insertCell().textContent = curNo
            newRow.insertCell().textContent = myForm.inputNL.value
            newRow.insertCell().textContent = myForm.inputJK.value
            newRow.insertCell().textContent = myForm.inputNH.value
            newRow.insertCell().textContent = myForm.inputA.value
            newRow.insertCell().innerHTML = `<a onClick="onDelete(this)"><i class="fas fa-times"></i></a>` 
        } 
        resetForm();
    }
}

// 重置表单
function resetForm() {
    document.getElementById("no").value = "";
    document.getElementById("inputNL").value = "";
    document.getElementById("inputJK").value = "Pria";
    document.getElementById("inputNH").value = "";
    document.getElementById("inputA").value = "";
    selectedRow = null;
}

// 删除操作
function onDelete(td) {
    if (confirm('Apa kamu yakin ingin Menghapus Data ini?')) {
        row = td.parentElement.parentElement;
        hapusDataLocal(row);
        document.getElementById("myTable").deleteRow(row.rowIndex);
        resetForm();
        // 删除后重排序号,保证序号连续
        reSyncNumber()
    }
}

function hapusDataLocal(row) {    
    // 通过行首序号匹配存储的对应记录
    const curNo = row.cells[0].textContent
    const targetIndex = dataArr.findIndex(item => item.no == curNo)
    if(targetIndex > -1) {
        dataArr.splice(targetIndex, 1);
    }
    localStorage.setItem('dataArr', JSON.stringify(dataArr))
}

// 同步序号逻辑
function reSyncNumber() {
    number = dataArr.length
    dataArr.forEach((item, index) => {
        item.no = index + 1
        table.rows[index].cells[0].textContent = index + 1
    })
    localStorage.setItem('dataArr', JSON.stringify(dataArr))
}

// 表单校验
function validate() {
    isValid = true;
    if (document.getElementById("inputNL").value == "" || document.getElementById("inputJK").value == "" || document.getElementById("inputNH").value == "" || document.getElementById("inputA").value == "") {
        isValid = false;
        alert("Isi Semua Formnya dengan Benar!");
    } 
    return isValid;
}

修复点说明

  • 调整了no字段的赋值顺序,确保存储到localStorage的记录包含正确的序号
  • 重写了删除匹配逻辑,通过序号匹配存储中的对应记录,保证删除准确
  • 修复了localStorage存储的键名错误,避免存储数据丢失
  • 新增了序号同步逻辑,删除数据后自动重排序号,保证序号连续正确

内容的提问来源于stack exchange,提问作者irfanhfzh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:09:02