在页面加载/刷新时加载随机页面的脚本?

时间:2014-07-22 07:53:44

标签: javascript jquery html cycle

我正在寻找能够让我在根目录中随机选择一个页面的东西,以便在每次首次加载页面时加载并随后重新加载/刷新..我有一个index.html和index2 .html例如在根目录中略有不同。

我试过谷歌但是找不到任何我尝试过的东西都没有用。

我目前正在尝试使用的javascript是:

var howMany = 3;  // number of pages below, count them.

howMany = howMany-1
var page = new Array(howMany+1);

page[0]="index.html";
page[1]="index2.html";
page[2]="index.html";

function rndnumber(){
    var randscript = -1;
    while (randscript < 0 || randscript > howMany || isNaN(randscript)){
        randscript = parseInt(Math.random()*(howMany+1));
    }
    return randscript;
}
quo = rndnumber();
quox = page[quo];
location.href=(quox);

如果我在本地测试它似乎它可以工作,但由于某种原因它会陷入无限且自动重新加载/刷新循环。当我将其上传到服务器时,没有重新加载循环,但随机化不起作用,它只是加载index.html

我在这里设置了一个测试页面:http://www.samnorris.co.nz/test2/在根目录中同时包含index.html和index2.html

任何人都可以提供任何线索,为什么这可能无法正常工作和/或更好的解决方案?

谢谢!

3 个答案:

答案 0 :(得分:2)

javascript在页面加载时在客户端上执行。因此,每次加载页面时,它都会随机选择一个页面并重定向到该页面。然后该页面有一些JavaScript,当执行时,选择一个随机页面并加载,......

更好的解决方案是使用服务器端语言处理服务器上页面的服务。例如PHP。代码将是这样的:

的index.php

<?php
$randNumber = mt_rand(1,3);
if ( $randNumber == 1 )
{
    include 'index_1.html';
}
else
{
    include 'index_2.html';
}

答案 1 :(得分:1)

你必须以某种方式告诉脚本它已被重定向。这可能是使用location的哈希值来实现的:

if (location.hash === "#redirected") {
  location.hash = "";
}
else {
  quo = rndnumber();
  quox = page[quo];
  location.href=(quox) + "#redirected";
}

答案 2 :(得分:0)

使用与"index*.html"文件相同的目录中的以下内容创建单独的html文件:

<script type="text/javascript">
    var pages = [
        "index.html",
        "index2.html",
        "index3.html"
    ];

    function randomPage() {
        return pages[Math.round(Math.random() * (pages.length - 1))];
    }

    location.href= randomPage();
</script>
相关问题