首页 > 解决方案 > 尝试设置随机重定向主页?

问题描述

我正在帮助我的朋友建立一个网站,我正在尝试对其进行设置,以便主页随机重定向到其中一个页面,现在设置为三个,但能够添加更多。

目前它似乎在某些时候有效,但有时不会通过,而且它似乎比其他房间更容易重定向到其中一个房间?

<script type="text/javascript">

//RANDOMLY REDIRECTS TO A ROOM !

var doors = Math.floor(Math.random() * 3) + 1;

    if (doors == 1) {
      window.location.href = 
"http://sarahboulton.co.uk/kitchen.html";
      }

    else if (doors == 2) {
      window.location.href = 
"http://sarahboulton.co.uk/livingroom.html";
      }

    else if (doors == 3) {
      window.location.href = 
"http://sarahboulton.co.uk/chapelbedroom.html";
      }

</script>

标签: javascripthtmlredirectrandom

解决方案


使用文件名创建一个数组。选择一个随机数,它应该是数组的索引。这是代码

<script type="text/javascript">

//RANDOMLY REDIRECTS TO A ROOM !


var pages = [ 'Kitchen', 'livingroom', 'chapelbedroom' ];

var doors = Math.floor(Math.random() * ( pages.length - 1 ));

var url = 'http://sarahboulton.co.uk/' + pages[doors] + '.html';

window.location = url;



</script>

推荐阅读