[英]Script to load random page on page load/refresh?
我正在寻找可以让我在根目录中的页面在每次首次加载时进行随机选择加载的页面,并随后进行重新加载/刷新。.例如,我有一个index.html和index2.html根目录中彼此不同。
我已经尝试过Google了,但是找不到任何/尝试过的一切都无法正常工作。
我当前正在尝试使用的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
谁能提供任何线索为什么这可能无法正常工作和/或更好的解决方案?
谢谢!
javascript在页面加载时在客户端上执行。 因此,每次加载页面时,它都会随机选择一个页面并重定向到该页面。 该页面然后嵌入了一些JavaScript,这些JavaScript在执行时会选择一个随机页面并加载该页面,...
更好的解决方案是使用服务器端语言在服务器上处理页面的提供。 例如PHP。 该代码将是这样的:
index.php
<?php
$randNumber = mt_rand(1,3);
if ( $randNumber == 1 )
{
include 'index_1.html';
}
else
{
include 'index_2.html';
}
您必须以某种方式告诉脚本它已被重定向。 这可以通过使用位置的哈希值来实现:
if (location.hash === "#redirected") {
location.hash = "";
}
else {
quo = rndnumber();
quox = page[quo];
location.href=(quox) + "#redirected";
}
在与"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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.