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

如何编写删除HTML表格最后新增行的JS函数,附现有相关代码

实现删除表格最后新增行的方案

直接在你现有代码的基础上新增remove函数即可,同时可以优化原有add函数的操作逻辑,避免误改表格表头:

function add() {
  const name = document.getElementById('name').value
  const surname = document.getElementById('surname').value
  // 直接操作表格的tbody节点,不影响表头
  const tableBody = document.querySelector('#output tbody')
  tableBody.innerHTML += `<tr><td>${name}</td><td>${surname}</td></tr>`
}

function remove() {
  const tableBody = document.querySelector('#output tbody')
  const rowList = tableBody.querySelectorAll('tr')
  // 存在数据行时才执行删除,避免报错
  if (rowList.length) {
    tableBody.removeChild(rowList[rowList.length - 1])
  }
}

你页面上的删除按钮已经绑定了onclick="remove()"事件,替换原有JS代码后即可直接生效:每次点击删除按钮都会移除表格最后一行数据,没有数据行时点击不会产生异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:24:04