[英]How to create and add elements to the DOM in a loop
I want to append num
amount of img
elements to the DOM, and give each image an id
according to which num
it is. 我想附加
num
的量img
元素到DOM,并为每个图像的id
,根据该num
它。 I know I need a loop, so this is what I have so far: 我知道我需要一个循环,所以这是我到目前为止的内容:
window.onload = function makeImage(){ for(i=0;i<num;i++){ document.getElementById('test').innerHTML="<img id='i' src='img/image.jpg'/>"; } };
<div id="test"></div>
Here are some code snippets and comments that should help you. 以下是一些代码段和注释,它们可以为您提供帮助。 Where you have
id='i'
, it looks like you want this: '<img id="'+i+'"'
. 在
id='i'
,看起来像这样: '<img id="'+i+'"'
。 You concatenate in JavaScript using the +
sign, so close your string with a quote, then concatenate, then open the string up again. 您在JavaScript中使用
+
号进行连接,因此请用引号将字符串关闭,然后进行连接,然后再次打开该字符串。 It's easier to learn by breaking this up into steps. 将其分解为多个步骤,将更容易学习。 Here's the string without the value:
'<img id=""'
Then, you'll need to go in between the double quotes and close and open the string with single quotes, and concatenate i
, so this: '+i+'
. 这是不带值的字符串:
'<img id=""'
然后,您需要在双引号之间插入并关闭并用单引号打开字符串,然后将i
连接起来,因此: '+i+'
。 Altogether, you get '<img id="'+i+'"'
总共得到
'<img id="'+i+'"'
var num = 2; // addEventListener is better practice than onload window.addEventListener('load', function() { // get the element reference before the loop (no need to repeat this) var testElem = document.getElementById('test'); for(i = 0; i < num; i++) { // create an img element, this is better practice than using innerHTML var img = document.createElement('img'); img.src = "//placehold.it/100x100"; img.id = 'image'+i; testElem.appendChild(img); } });
<div id="test"></div>
You could also use innerHTML
by concatenating the new image as in the following example, but this has drawbacks. 您还可以通过串联新图像来使用
innerHTML
,如以下示例所示,但这有缺点。 Read more about createElement vs innerHTML here . 在此处阅读有关createElement与innerHTML的更多信息 。
var num = 2; window.addEventListener('load', function() { var testElem = document.getElementById('test'); for(i = 0; i < num; i++) { testElem.innerHTML+= '<img id="image'+i+'"src="//placehold.it/100x100">'; } });
<div id="test"></div>
Problem here is you are not appending images in loop, old image just get overridden by the new one. 这里的问题是您没有循环添加图像,旧图像只是被新图像覆盖。 Since you are using
=
operator. 由于您正在使用
=
运算符。
document.getElementById('test').innerHTML="<img id='i' src='img/image.jpg'/>";
-----------------------------------------^
Use +=
instead, also you need to concat i
value to get image unique ids: 使用
+=
代替,另外,您还需要连接i
值以获得图像唯一ID:
var html = ""; var num = 3 for (var i = 1; num >= i; i++) { html += '<img src="http://www.tatwellness.com/store/image/cache/data/homewelcome/no%20image-200x200.png" id="img' + i + '"/>'; } document.getElementById('test').innerHTML = html;
img { border: 1px solid grey; margin: 5px; }
<div id="test"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.