我想在图像本身旁边显示图像的名称

时间:2013-10-24 17:29:07

标签: javascript arrays image

我还有一个关于数组的基本javascript问题。

我有一个简单的代码,每次加载页面时都会加载一个随机图像。问题是我想在图像本身旁边显示图像的名称。我似乎无法弄清楚如何。到目前为止,这是我的代码:

//I. Array of pictures that will randomly appear

var plaatjes = new Array ( );
plaatjes[0] = "burger.png";
plaatjes[1] = "tomaat.png";
plaatjes[2] = "aardappel.png";
plaatjes[3] = "sla.png";

//II. function to generate number from 0 to n

function randomplaatje (n)
{
 return ( Math.floor ( Math.random ( )*0.9999999999999999* (n + 1)) );
}

//III. assign any random number from 0 to 2 to x.

x = randomplaatje(3);

//IV. display the image 

document.write('<img alt="randomplaatje" src="' + plaatjes[x] + '"/>');

是否也可以在数组内的图像中添加alt-tags?它们可以在文本框中的图像旁边显示。

提前致谢!

3 个答案:

答案 0 :(得分:1)

一种解决方案是在数组中使用对象。

    var plaatjes = [
      {src:"burger.png","name":"This is a burger"},
      {src:"tomaat.png","name":"This is a tomaat"},
      {src:"aardappel.png","name":"This is a aardappel"},
      {src:"sla.png","name":"This is a sla"}
];

function randomplaatje (n)
{
 return ( Math.floor ( Math.random ( )*0.9999999999999999* (n + 1)) );
}

//Assign any random number from 0 to 2 to x.
x = randomplaatje(3);


// The image source is plaatjes[x].src and the image name is plaatjes[x].name so creating an image with its name next to it could be done this way for instance :

document.write('<img src=' + plaatjes[x].src + '/>');
document.write(plaatjes[x].name);

答案 1 :(得分:0)

您的数组不必只是一个字符串数组,它可以是一个包含文件名和替代文本的对象文字数组:

var plaatjes = new Array ( );
plaatjes[0] = {filename: "burger.png", altText: "this is a burger"};
plaatjes[1] = ...

然后你可以:

document.write('<img alt="' + plaatjes[x].altText+ '" src="' + plaatjes[x].filename + '"/>');

但是megawac建议创建节点并附加它们肯定比使用document.write更好。与使用document.write相比,它使您可以更好地控制DOM的构造方式。如果你使用像JQuery这样的库,那就更容易了。

答案 2 :(得分:0)

一种方法:

在您的页面中创建两个div:

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

将分别用作显示图像及其标题的容器。

然后,在您的javascript代码中,一旦您计算了要显示的图像的随机索引,只需“填充”您的容器,例如:

document.getElementById("image").innerHTML = '<img alt="randomplaatje" src="' + plaatjes[x] + '"/>';
document.getElementById("caption").innerHTML = plaatjes[x];