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

为什么使用forEach循环给多个div添加按钮时仅最后一项生效?

问题产生原因

你在循环外仅调用了一次document.createElement('div'),全局只生成了唯一的一个按钮DOM实例。DOM的append()方法对已存在于文档中的元素执行的是「移动」操作而非复制操作:每次循环把这个按钮插入当前column时,都会先把它从上一个父节点中移除,再挂载到当前column下,所以循环结束后按钮只会留在最后一次遍历的column中。

解决方法

有两种常用的修复方案:

  • 方案一:将按钮创建逻辑放到循环内部,每次遍历都生成独立的新按钮实例
const columns = document.querySelectorAll('.hcolumn');

columns.forEach(column => {
  const button = document.createElement('div');
  button.innerText = 'Expand text';
  button.classList.add('button');
  column.append(button)
});
  • 方案二:如果需要复用已创建的按钮模板,可以调用cloneNode(true)深拷贝元素后再插入
const columns = document.querySelectorAll('.hcolumn');
const buttonTemplate = document.createElement('div');
buttonTemplate.innerText = 'Expand text';
buttonTemplate.classList.add('button');

columns.forEach( column => {
  // true参数表示深拷贝,会复制元素的所有子节点和属性
  const newButton = buttonTemplate.cloneNode(true);
  column.append(newButton)
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 13:00:03