使用cookies通过math.random更改网页

时间:2014-10-20 08:40:35

标签: javascript html cookies

我正在寻找一种通过列表更改网页而无需两次获得同一页面的方法。我试过洗牌,但是当加载新页面时,它只是重新加载脚本。所以我想我需要使用某种cookie。但是我对javascript很新。有人可以帮帮我吗?

我正在考虑这样的事情,只是用某种形式的cookie:

var pages = ['sang1.html','sang2.html','sang3.html','sang4.html','sang5.html','sang6.html','sang7.html','sang8.html','sang9.html','sang10.html','sang11.html','sang12.html','sang13.html','sang14.html','sang15.html','sang17.html','sang18.html','sang19.html','sang20.html','sang21.html''sang22.html','sang23.html','sang24.html','sang25.html','sang26.html','sang27.html','sang28.html','sang29.html','sang30.html','sang31.html','sang32.html''sang33.html','sang34.html','sang35.html'];
var page = Math.floor((Math.random() * pages.length) + 1);
window.location.href = pages[page];
pages.splice(page);

2 个答案:

答案 0 :(得分:0)

 var page = pages[Math.floor(Math.random() * pages.length)]
 window.location.href = pages[page]

答案 1 :(得分:0)

以下是使用 localstorage 的基本解决方案,因为往返行程不会是一个好主意

var pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
var page, visitedPages = JSON.parse(localStorage.getItem("visitedPages"));
if (visitedPages === null) {
    visitedPages = [];
}
var unVisitedPages = difference(visitedPages, pages);
if(unVisitedPages.length === 0){//All pages visited at once
    //add your logic when all page visited
}
else{
    page = unVisitedPages[Math.floor(Math.random() * unVisitedPages.length)];
    localStorage.setItem("visitedPages", JSON.stringify(visitedPages.push(page)));
    window.location.href = page; //append if you want to kill cache"?ck="+new Date().getTime()
} 

function difference(a,b){//b -a
    var c = [];
    for(var i=0; i< b.length; i++){
        if(a.indexOf(b[i]) === -1){
            c.push(b[i]);
        }
    }
    return c;
}