如何在不使用innerHTML的情况下在javascript中将图像元素添加到div?

时间:2017-02-17 02:14:55

标签: javascript html tags

我正在尝试使用javascript将图像添加到html页面,我必须在不使用innerHTML的情况下执行此操作。我似乎无法让图像出现。

的javascript

var galleryPhotos = ["gallery/galleryphoto0.jpg", "gallery/galleryphoto1.jpg", "gallery/galleryphoto2.jpg", "gallery/galleryphoto3.jpg", "gallery/galleryphoto4.jpg"];

function newImage(){

var ele0 = document.createElement("img");
var image = document.getElementById("image");
ele0.scr = galleryPhotos[0];
image.appendChild(ele0);

var ele1 = document.createElement("img");
var image = document.getElementById("image");
ele1.scr = galleryPhotos[1];
image.appendChild(ele1);

var ele2 = document.createElement("img");
var image = document.getElementById("image");
ele2.scr = galleryPhotos[2];
image.appendChild(ele2);

var ele3 = document.createElement("img");
var image = document.getElementById("image");
ele3.scr = galleryPhotos[3];
image.appendChild(ele3);

var ele4 = document.createElement("img");
var image = document.getElementById("image");
ele4.scr = galleryPhotos[4];
image.appendChild(ele4);

}

我想把它放入html中

<div id="image"></div>

使用chromes调试工具对我没有任何帮助。

2 个答案:

答案 0 :(得分:2)

您有错字:scr应为src

答案 1 :(得分:0)

试试这个:

var galleryPhotos = ["gallery/galleryphoto0.jpg", "gallery/galleryphoto1.jpg", "gallery/galleryphoto2.jpg", "gallery/galleryphoto3.jpg", "gallery/galleryphoto4.jpg"];

function newImage(){

     var image = document.getElementById("image");
     var i = 0;
     while(galleryPhotos[i]){
         el = document.createElement("img");
         el.src = galleryPhotos[i];
         image.appendChild(el);
         i++;
     }

}