在最后一张幻灯片后加载新页面的javascript幻灯片

时间:2013-04-18 00:09:30

标签: javascript slideshow

抱歉,我对JS很新。我有一个基本的html页面,我已经放入幻灯片,每次点击都可以推进幻灯片。我想要发生的是当用户点击下一个并在最后一张幻灯片上时将其更改为新页面。我的HTML:

<div id="images">
    <img id="image1" src="http://www.lorempixel.com/960/580/sports" />
    <img id="image2" src="http://www.lorempixel.com/960/580/cats" />
    <img id="image3" src="http://www.lorempixel.com/960/580/food" />
    <img id="image4" src="http://www.lorempixel.com/960/580/people" />
</div>

我的JS看起来像这样:

var max = 4;

function goToNext() {
    var hash = String(document.location.hash);
    if (hash && hash.indexOf(/image/)) {
        var newh = Number(hash.replace("#image", ""));
        (newh > max - 1) ? newh = 0 : void(null);
        document.location.hash = "#image" + String(newh + 1);
    } else {
        document.location.hash = "image1";
    }
}

function goToPrevious() {
    var hash = String(document.location.hash);
    if (hash && hash.indexOf(/image/)) {
        var newh = Number(hash.replace("#image", ""));
        (newh == 1) ? newh = 5 : void(null);
        document.location.hash = "#image" + String(newh - 1);
    } else {
   var url = window.location.href;

if (url.search("#image") > 0) {
    window.location.href = "strategy.html";
  }    
 }
}

2 个答案:

答案 0 :(得分:0)

改变这个:

(newh > max - 1) ? newh = 0 : void(null);
        document.location.hash = "#image" + String(newh + 1);

到此:

(newh > max - 1) ? window.location.href = "strategy.html" :
        document.location.hash = "#image" + String(newh + 1);

jsfiddle

答案 1 :(得分:0)

检查newh是否为零,

    if(newh == 0) 
        document.location.href = "strategy.html";

以下是所有代码DEMO

var max = 4;

function goToNext() {
    var hash = String(document.location.hash);
    if (hash && hash.indexOf(/image/)) {
        var newh = Number(hash.replace("#image", ""));
        (newh > max - 1) ? newh = 0 : void(null);

        if(newh == 0) 
            document.location.href = "strategy.html";
        else 
            document.location.hash = "#image" + String(newh + 1);
    } else {
        document.location.hash = "image1";
    }
}

function goToPrevious() {
    var hash = String(document.location.hash);
    if (hash && hash.indexOf(/image/)) {
        var newh = Number(hash.replace("#image", ""));
        (newh == 1) ? newh = max+1 : void(null);
        document.location.hash = "#image" + String(newh - 1);
    } else {
        document.location.hash = "image4";    
 }
}