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

为何我的JavaScript函数点击按钮时添加的表格行数逐次递增?

问题修复方案

问题根源

每次点击按钮时,myFunction都会被执行,而函数内部又给document新增了一个click事件监听器。点击第i次按钮时,已经累计绑定了i个监听器,每个监听器都会触发添加行的逻辑,所以会添加i行。

修复方式一:直接利用onclick的事件对象

修改按钮的onclick属性,传入事件对象,直接在函数内处理当前点击的按钮,不需要额外绑定全局点击事件:

  1. 按钮代码修改:
<button onclick="myFunction(event)" id="btn1">按钮1</button>
<button onclick="myFunction(event)" id="btn2">按钮2</button>
  1. JavaScript函数修改:
function myFunction(e) {
  // 声明局部变量,避免全局污染
  const table_body = document.getElementById("t_body");
  const element = e.target;
  
  if (element.tagName === "BUTTON") {
    const row = table_body.insertRow();
    const cell1 = row.insertCell();
    // 用outerHTML获取按钮的完整HTML代码,避免直接插入元素导致的问题
    cell1.innerHTML = element.outerHTML;
    
    const cell2 = row.insertCell();
    cell2.innerHTML = element.id;
    const cell3 = row.insertCell();
    cell3.innerHTML = element.id;
    const cell4 = row.insertCell();
    cell4.innerHTML = element.id;
    
    element.style.backgroundColor = "#004d00";
    element.style.color = "white";
  }
}

修复方式二:只绑定一次全局点击事件

将事件监听器的绑定逻辑移到函数外部,确保只执行一次,同时移除按钮上的onclick属性:

  1. 按钮代码修改:
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
  1. JavaScript代码修改:
// 页面加载完成后绑定一次点击事件
document.addEventListener('DOMContentLoaded', function() {
  const table_body = document.getElementById("t_body");
  
  document.addEventListener("click", (e) => {
    const element = e.target;
    if (element.tagName === "BUTTON") {
      const row = table_body.insertRow();
      const cell1 = row.insertCell();
      cell1.innerHTML = element.outerHTML;
      
      const cell2 = row.insertCell();
      cell2.innerHTML = element.id;
      const cell3 = row.insertCell();
      cell3.innerHTML = element.id;
      const cell4 = row.insertCell();
      cell4.innerHTML = element.id;
      
      element.style.backgroundColor = "#004d00";
      element.style.color = "white";
    }
  });
});

额外优化点

原代码中变量未用const/let声明,会成为全局变量,建议始终使用const(值不修改时)或let(值需要修改时)声明局部变量,避免全局命名污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:01:18