1

我正在学习 javascript,并试图制作一个非常简单的照片库。我的下一个按钮的工作原理就像是假设一次推进一张照片,但是当你点击上一张时,它会一直回到第一张图像而不是只返回一张图像,我不太明白为什么。非常感谢您的帮助。

它在这里的 jsbin 中:http: //jsbin.com/unijet/2/edit

我的代码是:

html:

  <div id="navContainer">
  <span id="prev"><a href="" onClick="return prev_img();">Prev</a></span>
  <span id="pg"></span>
  <span id="next"><a href="" onClick="return next_img();">Next</a></span>
  </div>

  <div id="imgContainer"><img src="" id="img"/></div>

JS:

var prev = document.getElementById("prev");
var next = document.getElementById("next");
var imge = document.getElementById("img");
var page = document.getElementById("pg");    

var imag = [
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/red-fox-manitoba_66703_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/martial-arts-india_66701_990x742.jpg?01AD=3Ha8VZ6-_SyLzHh6QoaApO6cxS3yLIp8X8QYWOgGUaWbdSUQ9pY9LJw&01RI=20FA22155E4E381&01NA=na",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/666/cache/egret-reflection-florida_66697_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/tornado-storm-saskatchewan_66707_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/penguin-south-georgia-island_66702_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/sunset-south-africa_66706_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/man-motorbike-india_66710_990x742.jpg"
];

var i = 0;

imge.setAttribute("src",imag[i]);
prev.innerHTML = "Prev";
page.innerHTML = i;

function next_img() {
    i++;
    page.innerHTML = i;
    imge.setAttribute("src",imag[i]);

    if (i == imag.length-1) {
        next.innerHTML = "Next";
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
    } else {
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
    }
    return false;
}

function prev_img() {
    i--;
    page.innerHTML = i;
    image.setAttribute("src",imag[i]);

    if (i === 0) {
        prev.innerHTML = "Prev";
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
    } else {
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
    }
    return false;
}        
4

1 回答 1

1

在 prev_img() 函数更改

image.setAttribute("src",imag[i]);

imge.setAttribute("src",imag[i]);
于 2013-05-15T14:26:16.477 回答