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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:15:22