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

如何复制同结构不同id/name的div内容并保留目标元素属性?

解决方案:保留目标子元素ID,批量替换内容

你之前用html()直接替换的问题在于,它会把源div里**所有子元素的完整HTML结构(包括ID)**都覆盖到目标div里,自然就把目标的ID换掉了。既然两个div的子元素结构是一一对应的,我们可以通过循环遍历的方式,只复制每个子元素的内容,而保留目标子元素的原有属性(比如ID)。

实现代码

JavaScript(jQuery)

// 获取目标容器和源容器的子元素集合
const targetKids = $('#current-1').children();
const sourceKids = $('#next-1').children();

// 循环处理每一对对应位置的子元素
targetKids.each(function(index) {
  // 只替换当前目标子元素的内容,保留它的ID等属性
  $(this).html(sourceKids.eq(index).html());
});

完整HTML示例

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="current-1">
  <div id="current[1]_div1">Some text for current - div1</div>
  <div id="current[1]_someelement2">Some text for current - someelement2</div>
</div>
<div id="next-1">
  <div id="next[1]_div1">Some text for next</div>
  <div id="next[1]_someelement2">Some text for next - someelement2</div>
</div>

<script>
$(function() {
  const targetKids = $('#current-1').children();
  const sourceKids = $('#next-1').children();
  
  targetKids.each(function(index) {
    $(this).html(sourceKids.eq(index).html());
  });
});
</script>

效果验证

运行后,current-1的子元素ID会被完整保留,只有内容被替换成next-1对应位置的内容:

<div id="current-1">
  <div id="current[1]_div1">Some text for next</div>
  <div id="current[1]_someelement2">Some text for next - someelement2</div>
</div>
<div id="next-1">
  <div id="next[1]_div1">Some text for next</div>
  <div id="next[1]_someelement2">Some text for next - someelement2</div>
</div>

健壮性优化(可选)

如果担心两个容器的子元素数量不一致(比如源比目标多,或者反过来),可以添加长度判断,避免索引越界:

const targetKids = $('#current-1').children();
const sourceKids = $('#next-1').children();
// 取两者中较小的长度,只处理存在对应子元素的部分
const maxCount = Math.min(targetKids.length, sourceKids.length);

for (let i = 0; i < maxCount; i++) {
  targetKids.eq(i).html(sourceKids.eq(i).html());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:41:19