在图像源数组和显示的JavaScript加载图像 [英] JavaScript load Images in an Array and Show in Image Source

查看:104
本文介绍了在图像源数组和显示的JavaScript加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的图像阵列

function initialize(){
//add our 10 images to our array
imgArray[imageNum++] = new imageItem(imageDir + "img1.jpg");
imgArray[imageNum++] = new imageItem(imageDir + "img2.jpg");
imgArray[imageNum++] = new imageItem(imageDir + "img3.jpg");

}
var totalImgs = imgArray.length;

我然后创建一个在我的HTML文件链接的功能:

I then create a function that is linked with a in my html file:

<button id="startButton" onclick="startImage()">Start</button>

function startImage(){

    document.getElementById("pic").setAttribute("src", imgArray[0].src);
}   

我的形象标签:&LT; IMG ID =PICSRC =HEIGHT =300WIDTH =500BORDER =0ALT =图像&GT;

这没有更新我的IMG的对象,我用萤火虫来看看DOM和我的数组被正确填充,但IMG SRC是不能设置?

My image tag : <img id="pic" src="" height="300" width="500" border="0" alt="image"> This fails to update my img object, i used firebug to look at the DOM and my array is being populated properly but the img src is not be set?

推荐答案

您的例子是不完整的。你需要显示的ImageItem 构造做什么(和它的约定使用大写字母在构造函数的第一个字符),所以:

Your example is incomplete. You need to show what the imageItem constructor does (and it's convention to use a capital letter for the first character in a constructor), so:

function ImageItem(src) {
  this.image = new Image();
  this.src = src.
}

在这里应该做的工作。您也似乎想 imgArray 作为一个全球性的,所以声明它为一个:

should do the job here. You also seem to want imgArray as a global, so declare it as one:

var imgArray;

function initialize(){
    //add our 10 images to our array 
    imgArray[imageNum++] = new imageItem(imageDir + "armory.jpg");

指定数组文本是一个容易一点:

Assigning an array literal is a bit easier:

    imgArray = [ new ImageItem(imageDir + "armory.jpg"),
                 new ImageItem(imageDir + "eddy.jpg"),
                 ...
                 new ImageItem(imageDir + "...")
    ];
}

var totalImgs = imgArray.length;

虽然我不明白为什么你不只是数组直接分配文字,而不是与包装功能的麻烦。在 startImage 功能可有点整洁:

function startImage(){
    document.getElementById("pic").src = imgArray[0].src;
}

访问元素的属性是直接跨浏览器更可靠,小于使用的setAttribute 键入(其中有怪癖在某些浏览器)。

Accessing element properties directly is more reliable across browsers and less to type than using setAttribute (which has quirks in some browsers).

这篇关于在图像源数组和显示的JavaScript加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆