JPG 转成 div JS + 循环
JPG into div JS + loop
我只想这样做:
<div id="photos">
<script>
var i=0;
for (i=0;i<=5;i++)
{
document.createElement("<img src=\"" +"i/"+ i + ".jpg\"/>");
}
</script>
</div>
但它不起作用。怎么了?
创建 DOM 元素的正确方法是使用 document.createElement
API。这是一个例子:
var i = 0,
// Defining a temporary variable called tempImg, using `var` in the `for` body is a bad idea
tempImg,
// Select and cache the target parent element
targetParentElement = document.querySelector('#photos');
for (i = 0; i <= 5; i++) {
// create an HTMImageLElement object
tempImg = document.createElement("img");
// without beggining `/` the `src` has a relative path.
tempImg.src = "i/" + i + ".jpg";
tempImg.alt = "the image wasn't found on this server. Check the path!";
// append the image
targetParentElement.appendChild(tempImg);
}
这是 jsfiddle 上的演示:https://jsfiddle.net/udju8mzt/
我只想这样做:
<div id="photos">
<script>
var i=0;
for (i=0;i<=5;i++)
{
document.createElement("<img src=\"" +"i/"+ i + ".jpg\"/>");
}
</script>
</div>
但它不起作用。怎么了?
创建 DOM 元素的正确方法是使用 document.createElement
API。这是一个例子:
var i = 0,
// Defining a temporary variable called tempImg, using `var` in the `for` body is a bad idea
tempImg,
// Select and cache the target parent element
targetParentElement = document.querySelector('#photos');
for (i = 0; i <= 5; i++) {
// create an HTMImageLElement object
tempImg = document.createElement("img");
// without beggining `/` the `src` has a relative path.
tempImg.src = "i/" + i + ".jpg";
tempImg.alt = "the image wasn't found on this server. Check the path!";
// append the image
targetParentElement.appendChild(tempImg);
}
这是 jsfiddle 上的演示:https://jsfiddle.net/udju8mzt/