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 文件中的 a 链接的函数:
<button id="startButton" onclick="startImage()">Start</button>
function startImage(){
document.getElementById("pic").setAttribute("src", imgArray[0].src);
}
我的图像标签:
这无法更新我的 img 对象,我使用 firebug 查看 DOM 并且我的数组已正确填充,但未设置 img src?
I created an array of images
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;
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);
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
加载多个图像听起来像是您可能希望在不同项目中使用的功能。我建议创建一个可以处理图像数组并将图像对象附加到
的函数:
您还可以从您的应用程序调用
loadImage()
函数按钮:Load multiple images sounds like a functionality that you might want to user in different projects. I would suggest to create a function that can process your images array and append the image object to a
<div>
:You can also invoke the
loadImage()
function from your button:你的例子不完整。您需要显示
imageItem
构造函数的作用(构造函数中的第一个字符使用大写字母是惯例),所以:应该在这里完成这项工作。您似乎还希望将
imgArray
作为全局变量,因此将其声明为一个:分配数组文字要容易一些:
虽然我不明白为什么您不直接分配数组文字并且不用担心包装函数。
startImage
函数可以更简洁一些:直接访问元素属性在浏览器中更可靠,并且比使用
setAttribute
(在某些浏览器中存在怪癖)需要更少的输入。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:should do the job here. You also seem to want
imgArray
as a global, so declare it as one:Assigning an array literal is a bit easier:
Though I can't see why you don't just assign the array literal directly and not bother with the wrapper function. The
startImage
function can be a bit tidier:Accessing element properties directly is more reliable across browsers and less to type than using
setAttribute
(which has quirks in some browsers).像这样修改你的 javascript 函数并查看。
Modify your javascript function like this and see.