简体   繁体   English

显示图像阵列中的单个图像

[英]Show a single image from array of images

That's all I want to do. 这就是我要做的。 I'm very beginner in javascript but I just don't understand why this wouldn't work. 我是javascript的初学者,但是我不明白为什么这行不通。 I've looked across the depths of google but people are asking more complicated things. 我看过Google的各个方面,但人们在问更复杂的事情。 I literally just want to show an image I've stored in an array. 我只是想显示存储在数组中的图像。

$(document).ready(function(){
    var coolImage = new Array();

    coolImage[0] = "images/2.gif";

    var img = new Image();
    img.src = coolImage[0];

    document.write(img);
});

All I get on the page is [object HTMLImageElement] . 我在页面上得到的只是[object HTMLImageElement]

The brackets and object name indicate that you are writing the string representation of the Image object to the page. 方括号和对象名称表示您正在将Image对象的字符串表示形式写入页面。 Try replacing document.write(img); 尝试替换document.write(img); with: 与:

document.body.appendChild(img);

An example can be seen here 可以在这里看到一个例子

You're working with a JavaScript Image object, but you want an Image element: 您正在使用JavaScript Image对象,但是需要一个Image元素:

var image = document.createElement("img");
image.src = coolImage[0];
document.body.appendChild(image);

如果您使用的是jQuery,则可以使用:

$('body').append(img);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM