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

求助:如何用表单编辑表格单元格(原生JS,已实现增删)

解决方案:原生JS实现表格行编辑功能

步骤1:完善表格结构(示例)

假设你的基础表格结构如下(若你的表格结构不同,仅需调整单元格索引即可):

<table id="playerTable" border="1">
  <thead>
    <tr>
      <th>Nom</th>
      <th>Palmares</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>姆巴佩</td>
      <td>世界杯冠军、法甲冠军×5</td>
      <td>
        <button onclick="editRow(this)">编辑</button>
        <button onclick="deleteRow(this)">删除</button>
      </td>
    </tr>
    <tr>
      <td>梅西</td>
      <td>世界杯冠军×2、金球奖×8</td>
      <td>
        <button onclick="editRow(this)">编辑</button>
        <button onclick="deleteRow(this)">删除</button>
      </td>
    </tr>
  </tbody>
</table>

<!-- 你的编辑表单 -->
<form id="editform" style="display: none;">
  <fieldset>
    <legend>Informations du joueur</legend>
    <label>Nom: <input name="Name" /></label>
    <label>
      Palmares :
      <textarea name="address" cols="30" rows="3"></textarea>
    </label>
    <input type="button" value="Soumettre" onclick="Soumettre2()">
    <input type="button" value="Annuler" onclick="Cancel()" >
  </fieldset>
</form>

步骤2:定义全局变量记录当前编辑行

在JS代码开头添加变量,用于存储正在编辑的表格行:

let currentEditRow = null;

步骤3:实现editRow函数(点击编辑按钮触发)

该函数负责获取目标行数据、填充表单并显示表单:

function editRow(btn) {
  // 获取按钮所在的表格行
  currentEditRow = btn.closest('tr');
  // 提取行内单元格数据
  const name = currentEditRow.cells[0].textContent;
  const palmares = currentEditRow.cells[1].textContent;
  
  // 将数据填充到表单字段
  document.querySelector('#editform input[name="Name"]').value = name;
  document.querySelector('#editform textarea[name="address"]').value = palmares;
  
  // 显示编辑表单
  document.getElementById('editform').style.display = 'block';
}

步骤4:实现Soumettre2提交函数

该函数负责获取修改后的表单数据、更新表格行并隐藏表单:

function Soumettre2() {
  if (!currentEditRow) return;
  
  // 获取表单中的新数据
  const newName = document.querySelector('#editform input[name="Name"]').value.trim();
  const newPalmares = document.querySelector('#editform textarea[name="address"]').value.trim();
  
  // 可选:添加数据验证逻辑
  if (!newName) {
    alert('Nom不能为空');
    return;
  }
  
  // 更新表格行内容
  currentEditRow.cells[0].textContent = newName;
  currentEditRow.cells[1].textContent = newPalmares;
  
  // 隐藏表单并重置编辑状态
  document.getElementById('editform').style.display = 'none';
  currentEditRow = null;
}

步骤5:实现Cancel取消函数

function Cancel() {
  // 隐藏表单并重置编辑状态
  document.getElementById('editform').style.display = 'none';
  currentEditRow = null;
}

关键说明

  • 使用原生JS的closest('tr')方法快速定位按钮所在行,兼容现代浏览器
  • 通过cells[index]访问表格行的单元格,索引从0开始,需根据你的实际表格结构调整索引值
  • 全局变量currentEditRow用于关联表单与目标编辑行,确保提交时能精准更新对应行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:10:12