如何清空数组实现复用,解决记账应用EditText功能异常问题
代码问题及修复方案
核心问题梳理
- 未从选中行中正确获取单元格对象:代码中直接使用
cell0/cell1/cell2/cell3,但没有从当前选中的表格行里读取对应单元格的逻辑,实际每次读取的都是首次运行时可能产生的全局cell变量值,这是回填数据始终不变的根本原因。 - 类名参数多了空格:
getElementsByClassName("selected-row ")末尾多了冗余空格,会导致类名匹配异常。 - 清空数组的操作完全无效:
editName等数组是函数内部的局部变量,每次触发函数都会重新初始化为空数组,后续的splice清空操作没有任何意义,也不是导致数据重复的原因。 splice参数写法错误:splice第一个参数需要传入数字索引,你错误传入了数组[0],属于语法不规范。- 赋值逻辑位置错误:给输入框赋值的逻辑放在了while循环内部,会多次重复赋值,应该移到循环结束后统一执行。
- if判断逻辑无意义:
name/date等是DOM元素对象,只要存在就永远为真值,这个判断条件永远成立,没有实际作用。
修正后可正常运行的代码
document .getElementById("editSelection") .addEventListener("click", editSelection); function editSelection() { var editName = []; var editDate = []; var editAmount = []; var editRemarks = []; // 移除类名末尾的多余空格 let selectedRows = document.getElementsByClassName("selected-row"); while (selectedRows.length > 0) { const currentRow = selectedRows[0]; // 从当前选中行获取对应单元格 const cell0 = currentRow.cells[0]; const cell1 = currentRow.cells[1]; const cell2 = currentRow.cells[2]; const cell3 = currentRow.cells[3]; editName.push(cell0.innerText); editDate.push(cell1.innerText); editAmount.push(cell2.innerText); editRemarks.push(cell3.innerText); currentRow.parentNode.removeChild(currentRow); } // 循环结束后统一给输入框赋值 document.getElementById("inputName").value = editName.join("\n"); document.getElementById("inputDate").value = editDate.join("\n"); document.getElementById("inputAmount").value = editAmount.join("\n"); document.getElementById("inputRemarks").value = editRemarks.join("\n"); }
内容的提问来源于stack exchange,提问作者Ohwell
相关产品推荐
相关产品推荐

