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

使用JavaScript实现表格展示用户输入并点击按钮删除<tr>的问题求助

问题根源
  • 页面初始化时你提前将deleteProductBtn转成了deleteBtnArray,但此时页面还没有生成任何删除按钮,这个数组永远是空的,后续新增的删除按钮也不会自动加入该数组,导致删除事件从未成功绑定到按钮上。
  • 你给删除按钮同时设置了内联onclick事件和动态绑定监听,逻辑混乱:首次点击删除按钮时才会执行deleteProduct尝试绑定监听,首次点击不会触发删除逻辑,多次调用还会造成重复绑定。
  • 按钮位于form标签内,默认type属性为submit,点击会触发表单提交,因为事件绑定失效,你写的preventDefault没有生效,导致页面刷新。
修复方案

直接在生成删除按钮时传入当前项的索引,简化逻辑,无需额外绑定监听:

let data = [];
let speciesInput = document.querySelector('#speciesInput')
let breedInput = document.querySelector('#breedInput')
let messageBox = document.getElementById("display");
const addProductBtn = document.querySelector('#addValue')

addProductBtn.addEventListener('click', function (e) {
    e.preventDefault();
    let species = speciesInput.value;
    let breed = breedInput.value;
    data.push({
        species: species,
        breed: breed,
    });
    clearAndShow();
})  

function clearAndShow() {
    speciesInput.value = "";
    breedInput.value = "";
    messageBox.innerHTML = computeHTML();
}

function computeHTML() {
    let html = "<table>";
    // 遍历的时候带上索引
    data.forEach(function (item, index) {
        html += "<tr>";
        html += "<td>" + item.species + '&nbsp' + "</td>" 
        html += "<td>" + item.breed + "</td>"
        // 给按钮加type="button"避免提交,直接传当前索引到deleteProduct
        html += "<td>" + "<button type='button' class='deleteProduct' onclick='deleteProduct(" + index + ")'> &#8722; </button>" + "</td>"
        html += "</tr>"
    });
    html += "</table>"
    return html;
}

// 直接根据索引删除对应项
function deleteProduct(index) {
    // 删除data数组中对应索引的项
    data.splice(index, 1);
    // 重新渲染表格
    clearAndShow();
}

document.querySelector('#productForm').addEventListener('submit', function (e) {
    e.preventDefault();
})

注意确保你的form标签保留id="productForm"属性,避免表单默认提交行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:54:02