如何用随机生成的数字替换 window.location 的一部分?

How to replace a portion of window.location with a randomly generated number?

我正在尝试制作一个简单的游戏,其中的选择是一种幻觉。你有 4 个按钮可供选择,北、西、东和南,我希望每个按钮使用 math.random 生成一个随机数,然后使用 window.location 将它们带到相同的编号页面点击。

即有 100 html 个页面标记为 1.html、2.html、3.html,一直到 100.html,您从第 1.html 页开始,单击向北,随机生成的数字带你到 23.html,再次点击,79.html,再次点击,3.html,依此类推。

我知道如何使用window.location将您带到设置的页面,我知道如何math.random选择1-100之间的数字,但我不知道如何输入这两个元素一起做我想做的事。

<html>

<head>

<script>
function beginner()
{
document.getElementById("demo1").innerHTML=(Math.floor(Math.random()*100)+1);
}

</script>



</head>

<body>

<div id="header" style="clear: both; margin-bottom: 25px;">
pick a direction to go
</div> 

<div id="nav" style="float: left; ">
<center>

<input type="button" id="north" value="north" onclick="window.location='demo1';" /> <br />

<input type="button" id="west" value="west" onclick="randompage2();" /> 
<input type="button" id="east" value="east" onclick="randompage3();" /> <br />

<input type="button" id="south" value="south" onclick="randompage4();" />
</center>
</div>

</body>

</html>

您可以用 + 连接,所以我个人会这样做。

window.location = '/'+Math.floor(Math.random() * 100) + 1+'.html';

现在用JavaScript重定向用户的最好方法是window.location.replace()(因为它会发起一个HTTP请求)

所以:

window.location.replace("http://example.com/pages/"+(Math.floor(Math.random()*100)+1)+".html")

这只是简单的字符串连接。 了解 window.location on MDN

希望能帮到你!