照片库上一个按钮无法正常工作

时间:2013-05-15 14:17:59

标签: javascript photo-gallery

我正在玩学习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;
}        

1 个答案:

答案 0 :(得分:1)

在prev_img()函数中更改

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

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