问题描述:

These are the instructions:

"Have an image and two buttons, PREV and NEXT. Have 10 images in an array. When you click on NEXT, the next picture should display and when you click on PREV, the previous image should display."

This is what I wrote so far:

<html>

<head>

<title>Image Loop</title>

</head>

<body>

<img src="http://placekitten.com/500/200" id="image" style="height:150px; width:150px" />

<input type="button" value="Prev" name="previous_picture" onclick= nextImage();>

<input type="button" value="Next" name="next_picture"/>

<script>

function nextImage () {

var i = images.indexOf();

var imageSrc = document.getElementById("image").src=images[i];

for (i = weekdays.indexOf(day); i<weekdays.length; i++)

}

function prevImage () {

}

var images = new Array(

"http://placekitten.com/500/200",

"http://placekitten.com/499/200",

"http://placekitten.com/501/200",

"http://placekitten.com/500/199"

);

</script>

</body>

</html>

* the image should loop back around when it gets to the end of the array. I just don't know what I'm doing... :( *

网友答案:

Do some more investigations, this really shows too little effort.

I'll give you some pointers.

Javascript: Generic get next item in array

Javascript knows the modulus operation: https://msdn.microsoft.com/nl-nl/library/9f59bza0(v=vs.94).aspx

prev = (index + length - 1 ) % length

next = (index + 1 ) % length

prev needs prevImage() and next needs nextImage() functions

etc.

网友答案:

You have a few things off here.

To start with, take a look at how Array.indexOf() works: http://www.w3schools.com/jsref/jsref_indexof_array.asp

What are you trying to attempt with:
for (i = weekdays.indexOf(day); i<weekdays.length; i++)

After you find the index of the picture that is current, if index+1 would be greater than or equal to the length of the images array, then set index to 0.

网友答案:

Jsfiddle of a solution, using a small bit of jquery:

https://jsfiddle.net/cchhymtx/

Javascript:

var images = new Array(
    "http://placekitten.com/500/200",
    "http://placekitten.com/499/200",
    "http://placekitten.com/501/200",
    "http://placekitten.com/500/199");

function getCurrentImageIndex() {
    return images.indexOf(document.getElementById("image").src);
}

function next() {
    nextImage = (getCurrentImageIndex() + 1) % images.length;
    document.getElementById("image").src = images[nextImage];
}

function prev() {
    nextImage = (getCurrentImageIndex() - 1 + images.length) % images.length;
    document.getElementById("image").src = images[nextImage];
}
相关阅读:
Top