显示图像数组中的图像 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8810927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing an image from an array of images - Javascript
提问by Navigatron
I have a large image which is shown on my homepage, and when the user clicks the "next_img" button the large image on the homepage should change to the next image in the array.
我有一个大图像显示在我的主页上,当用户单击“next_img”按钮时,主页上的大图像应该更改为数组中的下一个图像。
However, the next arrow when clicked does nothing, and the main image on the homepage does not change.
但是,单击下一个箭头时什么也不做,主页上的主图像不会改变。
I need to do this in javascript.
我需要在 javascript 中做到这一点。
In the HTML:
在 HTML 中:
<!--Main Content of the page -->
<div id="splash">
<img src="images/img/Splash_image1.jpg" alt="" id="mainImg">
</div>
<div id="imglist">
<a href="javascript:nextImage('mainImg')"><img src="images/next_img.png" alt=""></a>
And then in the javascript file:
然后在 javascript 文件中:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'images/img/Splash_image3.jpg';
imgArray[3] = new Image();
imgArray[3].src = 'images/img/Splash_image4.jpg';
imgArray[4] = new Image();
imgArray[4].src = 'images/img/Splash_image5.jpg';
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0;i<imgArray.length;i++)
{
if(imgArray[i] == img)
{
if(i == imgArray.length)
{
var j = 0;
document.getElementById(element).src = imgArray[j].src;
break;
}
else
var j = i + 1;
document.getElementById(element).src = imgArray[j].src;
break;
}
}
}
Any help would be appreciated. Thanks.
任何帮助,将不胜感激。谢谢。
采纳答案by Zeta
Just as Diodeus said, you're comparing an Image
to a HTMLDomObject
. Instead compare their .src
attribute:
正如 Diodeus 所说,您将 anImage
与 a进行比较HTMLDomObject
。而是比较它们的.src
属性:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
回答by jfriend00
Here's a somewhat cleaner way of implementing this. This makes the following changes:
这是一种更简洁的实现方式。这进行了以下更改:
- The code is DRYed up a bit to remove redundant and repeated code and strings.
- The code is made more generic/reusable.
- We make the cache into an object so it has a self-contained interface and there are fewer globals.
- We compare
.src
attributes instead of DOM elements to make it work properly.
- 代码稍微干了一点,以删除冗余和重复的代码和字符串。
- 代码变得更通用/可重用。
- 我们把缓存做成一个对象,所以它有一个自包含的接口,并且有更少的全局变量。
- 我们比较
.src
属性而不是 DOM 元素以使其正常工作。
Code:
代码:
function imageCache(base, firstNum, lastNum) {
this.cache = [];
var img;
for (var i = firstNum; i <= lastnum; i++) {
img = new Image();
img.src = base + i + ".jpg";
this.cache.push(img);
}
}
imageCache.prototype.nextImage(id) {
var element = document.getElementById(id);
var targetSrc = element.src;
var cache = this.cache;
for (var i = 0; i < cache.length; i++) {
if (cache[i].src) === targetSrc) {
i++;
if (i >= cache.length) {
i = 0;
}
element.src = cache[i].src;
return;
}
}
}
// sample usage
var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");
Some advantages of this more object oriented and DRYed approach:
这种更加面向对象和 DRYed 方法的一些优点:
- You can add more images by just creating the images in the numeric sequences and changing one numeric value in the constructor rather than copying lots more lines of array declarations.
- You can use this more than one place in your app by just creating more than one imageCache object.
- You can change the base URL by changing one string rather than N strings.
- The code size is smaller (because of the removal of repeated code).
- The cache object could easily be extended to offer more capabilities such as first, last, skip, etc...
- You could add centralize error handling in one place so if one image doesn't exist and doesn't load successfully, it's automatically removed from the cache.
- You can reuse this in other web pages you develop by only change the arguments to the constructor and not actually changing the implementation code.
- 您可以通过在数字序列中创建图像并在构造函数中更改一个数值而不是复制更多行的数组声明来添加更多图像。
- 只需创建多个 imageCache 对象,您就可以在您的应用程序中不止一处使用它。
- 您可以通过更改一个字符串而不是 N 个字符串来更改基本 URL。
- 代码量更小(因为去除了重复代码)。
- 缓存对象可以轻松扩展以提供更多功能,例如第一个、最后一个、跳过等...
- 您可以在一个地方添加集中错误处理,这样如果一个图像不存在并且没有成功加载,它会自动从缓存中删除。
- 您可以在您开发的其他网页中重用它,只需更改构造函数的参数,而不实际更改实现代码。
P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.
PS 如果你不知道 DRY 代表什么,它是“不要重复你自己”,基本上意味着你不应该有很多相似代码的副本。任何时候你都有它,它应该以某种方式减少到一个循环或函数或一些不需要大量类似代码副本的东西。最终结果将更小,通常更易于维护并且通常更易于重用。
回答by Hooby
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
此外,在检查最后一张图像时,您必须与 进行比较,imgArray.length-1
因为例如,当数组长度为 2 时,我将取值 0 和 1,它不会达到值 2,因此您必须与 length-1 进行比较不是长度,这里是固定线:
if(i == imgArray.length-1)
回答by hakim
This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:
这是一个简单的示例,并尝试使用一些修改将其与您的示例结合起来。我更喜欢您将所有图像设置在一个数组中,以使您的代码更易于阅读和更短:
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
"_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex = (imageIndex + 1) % imageArray.length;
}
setInterval(changeImage, 5000);
回答by Diodeus - James MacFarlane
Here's your problem:
这是你的问题:
if(imgArray[i] == img)
You're comparing an array element to a DOM object.
您正在将数组元素与 DOM 对象进行比较。
回答by rahul
<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}