生成链接顺序顺序而不是随机顺序

时间:2013-11-29 15:14:16

标签: javascript

我正在尝试按顺序生成以下链接,然后在列表顶部重新启动,但不要随机化链接

 <script>
 var randomlinks=new Array()

 randomlinks[0]="http://java.com"
 randomlinks[1]="http://javascriptkit.com"
 randomlinks[2]="http://dynamicdrive.com"
 randomlinks[3]="http://cnn.com"
 randomlinks[4]="http://www.geocities.com"

 function randomlink(){
 window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)]
 }
 //-->
 </script>

2 个答案:

答案 0 :(得分:0)

var links = ["http://java.com", "another url here", ...];
nextIndex = 0;
cycleLinks();

function cycleLinks()
{
    // get next link
    nextLink = links[nextIndex];
    nextIndex = nextIndex % links.length;

    // display link
    window.location = nextLink;

    // after a while, change the link
    // if you don't do that, the displayed webpage will probably disappear too fast
    setTimeout(cycleLinks, 1000);
}

答案 1 :(得分:0)

使用cookies,并存储最后一个共享链接。

var randomlinks=new Array();
    randomlinks[0]="http://java.com"
    randomlinks[1]="http://javascriptkit.com"
    randomlinks[2]="http://dynamicdrive.com"
    randomlinks[3]="http://cnn.com"
    randomlinks[4]="http://www.geocities.com"

 function randomlink(){
    var itemsCount = randomlinks.length;
    var newSuggest = getCookie("lastlink");

    if(typeof newSuggest !== "undefined"){
        newSuggest = parseInt(newSuggest);
        if((newSuggest+1)<itemsCount){
            newSuggest++;
        }else{
            newSuggest=0;
        }
        setCookie("lastlink",newSuggest,30);
        window.location = randomlinks[newSuggest];

    }else{
        setCookie("lastlink",0,30);
    }
 }



function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(cookie) {
    return document.cookie.split(';').reduce(function(prev, c) {
        var arr = c.split('=');
        return (arr[0].trim() === cookie) ? arr[1] : prev;
    }, undefined);
}