0

对不起,我对 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";
  }    
 }
}
4

2 回答 2

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

于 2013-04-18T00:37:37.657 回答
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";    
 }
}
于 2013-04-18T00:38:48.210 回答