JS无法向Table添加行求助:表单传入值已确认正确
问题分析与修复
核心错误
你代码里的关键问题是重复读取.value属性:
const inputListNameText = inputListName.value; // 这里已经拿到了输入框的字符串值 // ... listCell.textContent = inputListNameText.value; // 错误:inputListNameText是字符串,没有.value属性
字符串类型没有.value属性,这会导致listCell的内容变成undefined,虽然行被添加了,但看不到实际内容。
修复后的代码
把listCell.textContent那行改成直接使用inputListNameText,同时匹配现有表格行的结构,避免布局错乱:
const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ list_name: inputListNameText }), }).then(response => response.json()) .then(data => { console.log(data); console.log(inputListNameText); const tableBody = document.querySelector('#tbody'); const newRow = document.createElement('tr'); // 匹配现有行结构:添加带复选框的<th> const checkboxCell = document.createElement('th'); checkboxCell.setAttribute('scope', 'row'); const checkbox = document.createElement('input'); checkbox.className = 'todo__checkbox'; checkbox.type = 'checkbox'; checkboxCell.appendChild(checkbox); // 添加内容单元格 const listCell = document.createElement('td'); listCell.className = 'text-break'; listCell.textContent = inputListNameText; // 修正为直接使用变量值 newRow.appendChild(checkboxCell); newRow.appendChild(listCell); tableBody.appendChild(newRow); }) }
额外说明
原表格的行包含一个带复选框的<th>和一个<td>,修复后的代码保持了结构一致性,避免表格布局错位。如果不需要复选框,可以只保留内容<td>,但需确保和现有行结构统一。
内容的提问来源于stack exchange,提问作者Bo Salinas
相关产品推荐
相关产品推荐

