首页 > 解决方案 > 如何在 Javascript 中使用 DOM 在 HTML 父标签中多次插入相同的图像?

问题描述

我想在</p>Javascript 的帮助下在我的 HTML 标记中插入相同的图像 3 次。像下面

<p class="image flex">
    <img
        src="images/Heart.png"
        alt="character image"
        class="images img"
    />
    <img
        src="images/Heart.png"
        alt="character image"
        class="images img"
    />
    <img
        src="images/Heart.png"
        alt="character image"
        class="images img"
    />
</p>

为了在 JavaScript 中添加它,我使用了这段代码。

const img = document.querySelector('.image');
const image = new Image();
image.src = "images/Heart.png";
image.alt = 'character img';
image.classList.add('images', 'img');

for (let i = 0; i < 3; i++) {
    img.appendChild(image);
}

这段代码只给出这样的输出。

<p class="image flex">
    <img
        src="images/Heart.png"
        alt="character img"
        class="images img"
    />
</p>

标签: javascripthtml

解决方案


您只创建了一次元素。这样你在同一个父元素中追加了 3 次相同的元素,在这种情况下,这基本上只会浪费 CPU 资源。

实际上,基于 MDN 并感谢 @araraonline 指出这一点

如果给定的子节点是对文档中现有节点的引用,则 appendChild() 将其从当前位置移动到新位置(不需要在将节点附加到其他节点之前将其从其父节点中删除)。

This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.

What you should do is create the element inside the loop.

const img = document.querySelector('.image');

for (let i = 0; i < 3; i++) {
  const image = new Image()
  image.src = "images/Heart.png";
  image.alt = 'character img';
  image.classList.add('images', 'img');
  img.appendChild(image);
}

推荐阅读