[英]how to append multiple img-child elements to a DOM element with JS?
I want to add multiple, same img-elements to a div element.我想向 div 元素添加多个相同的 img 元素。 Why can't I just use appendChild a couple times?
为什么我不能只使用 appendChild 几次?
For instance:例如:
divelement.appendChild(imgelement);
divelement.appendChild(imgelement);
divelement.appendChild(imgelement);
will result in将导致
<div>
<img></img>
</div>
But how can I achieve the following?但我怎样才能实现以下目标?
<div>
<img></img>
<img></img>
<img></img>
</div>
The imgelement
needs to be a new instance. imgelement
需要是一个新实例。 If you add the same child, it will do nothing.如果你添加同一个孩子,它什么也不做。
const divElement = document.querySelector('#target'); const imgElement = document.createElement('img'); divElement.append(imgElement); // Original reference divElement.append(imgElement); // ^ Same reference divElement.append(imgElement); // ^ Same reference
img { width: 100px; height: 100px; background: red; }
<div id="target"></div>
You need to create a new image instance for each append action:您需要为每个 append 操作创建一个新的图像实例:
const divElement = document.querySelector('#target'); const createImgElement = () => document.createElement('img'); divElement.append(createImgElement()); divElement.append(createImgElement()); divElement.append(createImgElement());
img { width: 100px; height: 100px; background: red; }
<div id="target"></div>
This way should work.这种方式应该有效。
var div = document.getElementById('myId');
for(var i = 0; i < 3; i++){
var img = document.createElement('img');
div.appendChild(img);
}
I think You are appending same child 3 times.我认为您正在附加同一个孩子 3 次。
an working solution is here -一个可行的解决方案在这里 -
const myParent = document.getElementById("someDiv"); const myImg1 = document.createElement("img"); myImg1.src = "https://picsum.photos/200/300"; myParent.append(myImg1); const myImg2 = document.createElement("img"); myImg2.src = "https://picsum.photos/200/300"; myParent.append(myImg2); const myImg3 = document.createElement("img"); myImg3.src = "https://picsum.photos/200/300"; myParent.append(myImg3);
*{ margin:0; padding:0; box-sizing:border-box; } #someDiv{ width:500px; height:200px; background-color:green; margin:auto; display:flex; } img{ margin-right:10px; }
<div id = "someDiv"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.