0

我很难找到问题的答案。我有一个简单的幻灯片放映,其中有下一个和上一个按钮,但是当我点击上一个按钮时,它会在第一张图像处停止。我希望它从第一张图像到最后一张,但找不到正确的结果。这就是我所拥有的:

window.onload = function () {
    var listNode = $("image_list");
    var captionNode = $("caption");
    var imageNode = $("image");

    var links = listNode.getElementsByTagName("a");

    // Process image links
    var i, linkNode, image;
    var imageCache = [];
    for (i = 0; i < links.length; i++) {
        linkNode = links[i];

        // Preload image and copy title properties
        image = new Image();
        image.src = linkNode.getAttribute("href");
        image.title = linkNode.getAttribute("title");
        imageCache.push(image);
    }

    //next button handler
    var nextButton = $("next");
    var imageCounter = 0;
    nextButton.onclick = function () {
        imageCounter = (imageCounter + 1) % imageCache.length;
        image = imageCache[imageCounter];
        imageNode.src = image.src;
        captionNode.firstChild.nodeValue = image.title;
    }

    //previous button handler
    var prevButton = $("previous");
    var imageCounter = 0;
    prevButton.onclick = function () {
        imageCounter = (imageCounter - 1) % imageCache.length;
        image = imageCache[imageCounter];
        imageNode.src = image.src;
        captionNode.firstChild.nodeValue = image.title;
    }
4

1 回答 1

0

这是我要做的(我不完全确定语法):

//previous button handler
var prevButton = $("previous");
var imageCounter = 0;
prevButton.onclick = function () {
    imageCounter = (imageCounter - 1) % imageCache.length;

    //------- INSERTED CODE --------//
    imageCounter = imageCounter >= 0 ? imageCounter : imageCache.length - 1 ; //Meaning you've reached the first image and want to go to the last
    //------- INSERTED CODE --------//

    image = imageCache[imageCounter];
    imageNode.src = image.src;
    captionNode.firstChild.nodeValue = image.title;
}

解释:

所以在设置之后imageCounter,你检查它的值。如果它等于或大于零,则保留该值。如果不是(意味着您要转到最后一张图像),请将其值设置为imageCache负 1 的长度,因为数组索引从 0 开始计数。:)

于 2013-05-30T13:58:42.000 回答