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

JavaScript动态生成表格行:为每个td添加input及name属性

问题解决:动态添加带对应输入框的表格行

原代码的核心问题是只创建了一个<input>元素,DOM元素无法同时挂载在多个父节点下,每次调用appendChild都会把这个输入框从之前的单元格移到下一个,最终只有最后一个单元格能显示输入框。同时也没给新输入框设置和初始行对应的name属性,导致表单提交时无法正确获取所有行的数据。

修改后的JavaScript代码

let srno = 1; // 用let声明变量,避免全局污染

function CreateTables() {
  const table = document.querySelector('table');
  const newRow = table.insertRow(-1);

  // 1. 创建序号单元格
  const cell1 = newRow.insertCell(0);
  cell1.textContent = ++srno;

  // 2. 定义各输入列的配置:name、type
  const inputConfigs = [
    { name: 'nameofapp', type: 'text' },
    { name: 'watts', type: 'number' },
    { name: 'no', type: 'number' },
    { name: 'hours', type: 'number' }
  ];

  // 3. 循环创建带输入框的单元格
  inputConfigs.forEach(config => {
    const cell = newRow.insertCell();
    const input = document.createElement('input');
    input.classList.add('textbox');
    input.name = config.name;
    input.type = config.type;
    cell.appendChild(input);
  });
}

const addBtn = document.querySelector('.Addbutton');
addBtn.addEventListener('click', CreateTables);

额外优化提示

原HTML中Addbutton的type="submit"可以改成type="button",因为它不在<form>标签内,点击submit类型按钮会触发表单提交,可能导致页面刷新,影响添加行的体验:

<button type='button' class='Addbutton'>Add</button>

代码说明

  • 为每个输入列创建独立的<input>元素,避免DOM元素重复挂载的问题
  • 通过inputConfigs数组统一管理各输入框的name和type,和初始行的表单字段保持一致,确保表单提交时能正确收集所有行的数据
  • 使用循环简化代码,后续如果需要调整列数或配置,只需修改inputConfigs数组即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:03:37