javascript - JPG转div JS+循环

标签 javascript html loops jpeg

我只想这样做:

<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/

关于javascript - JPG转div JS+循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125155/

相关文章:

javascript - 单击 li 标记中的 href 时链接未打开

c++ - 下降循环比上升循环更有效吗?

javascript - $.each 只是遍历我数组中的最后一项......为什么会这样?

javascript - 当图像已经具有 href 标签时,如何将其设为链接?

javascript - 如何获取鼠标单击 Canvas 元素的坐标?

php - 如果达到 div 高度,则强制将内容放到新的打印页面上

javascript - 如何使用 AngularJS 动态获取文本框值

javascript - 如何将 <stdio.h> 视为简单文本而不是 html 标签

java arrayList循环性能

ruby-on-rails - 编写具有字符串条件数组的 ActiveRecord 查询