0

我正在学习 HTML 和 JavaScript,首先,我正在创建一个使用 for 循环显示 4 张图像的简单网站。但是,当我在浏览器中查看时,我只能看到图像的名称,而看不到图像本身。这是我的代码:

<html xmlns="http://www.w3.org/1999/xhtml" >
<div id = "products" align = "center">

 <script>

  function showImages() {
    var productImg = new Array("a.png", "b.png", "c.png","d.png");
    var x = " ";

     for (var i = 0; i < productImg.length; i++) {

        var image = productImg[i];
        x += image;

    }

    var getImg = document.getElementById('products').innerHTML = x;
}



  </script>
  </div>
  <body onload = "showImages()">

   </body>
   </html>

我在这里想念什么?提前致谢。

4

2 回答 2

1

这应该有效。您的图像需要 img 标签 :) 对于您缺少什么的问题,我必须用 HTML 回答几乎所有内容。

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <script>
        function showImages() {
            var productImg = ["a.png", "b.png", "c.png","d.png"];
            var x = "";
            for (var i = 0; i < productImg.length; i++) {
                var image = productImg[i];
                x += '<img src="' + image + '"/>';
            }
            var getImg = document.getElementById('products').innerHTML = x;
        }
        </script>
    </head>
    <body onload="showImages()">
    <div id="products" align="center"></div>
    </body>
</html>
于 2013-10-23T22:11:25.840 回答
0

Joni 的回答非常正确 - 但是在您学习时,请记住 HTML“只是”一个结构化文本文档,这将使您走得更远。一旦你准备好动态创建内容,就准备好学习大量的 DOM。但是,你似乎已经知道一些代码,所以这就是成功的一半。;)

为了让您了解如何使用 JS 执行此操作,您正在寻找的是Image对象。您可以通过编写类似...的内容来创建新图像var myPicture = new Image();。就目前而言,这在您的文档中尚不存在,并且它没有源 - 资源的路径,但您确实有对新图像的引用,您可以使用它来做事。

src你可以通过改变它的属性来给它一个来源,就像这样myPicture.src="a.png";:但是,您必须记住(这很重要)加载该图像的操作是异步的。这意味着如果您要将图像添加到文档中,则在加载图像之前您将看不到任何内容。图像是开始理解这一点的好地方。尝试在您的控制台(chrome 中的开发人员工具)中使用这些命令,看看它有什么不同。

var myPicture = new Image();
myPicture.src = 'a.png';
document.body.appendChild(myPicture); // may or may not show the image, depending on how long it takes to load, but should be almost instant on a localhost or file

var myEmptyPicture = new Image();
document.body.appendChild(myEmptyPicture); // you will see the empty image tag in the document
myEmptyPicture.onload = function(){
  console.log('I have finished loading the picture!')
};
myEmptyPicture.src = 'b.png'; // you kept the reference to the image, so you can change its src attribute even while it is in the document - this is important for more advanced stuff, and it should log a message to your console

// last one, this will insert itself into the document once it has loaded
myAutomaticPicture = new Image();
myAutomaticPicture.onload = function(){
  console.log('picture loaded, inserting into document');
  document.body.appendChild(myAutomaticPicture); // should see it in the document now
}
myAutomaticPicture.src = 'c.png';

onload 属性的特殊之处在于它以一个函数作为其值。当图像完成加载时调用此函数。

要尝试的事情,更改 DOM 中已有元素的 src 属性,或使用 document.createElement 方法制作其他元素并附加它们(例如:)var heading = document.createElement('h1'); heading.innerHTML='hello'; document.appendChild(heading);

一旦你开始看到这一切是如何结合在一起的,这会很有趣……

于 2013-10-23T23:03:39.560 回答