javascript - 如何在 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>
解决方案
您只创建了一次元素。这样你在同一个父元素中追加了 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);
}
推荐阅读
- angular - 带有 JSON 的 Angular 中的动态菜单
- attachment - 如何知道 Corda 事务中的所有附件都已收到
- python-3.x - 如何使用python将字符串日期时间转换为int
- python - 如何从文本文件中检索计数并按最大数排序然后在python上显示
- angular - NgSwitch - 行为出乎意料,`No provider for NgSwitch` - 出现异常
- solace - 只有当它有一个活跃的订阅者时才会创建安慰主题吗?
- jquery - 将鼠标悬停在滑块的左侧或右侧时,如何将光标转向左侧或右侧图标?
- javascript - 如何为表单生成动态唯一 ID,该表单是弹出表单以评论每篇文章但它获取最后一篇文章 ID
- angular - Ionic 4 应用程序不能作为 Electron 应用程序运行
- javascript - 如何从前端订购一系列 api 调用?