【问题标题】:How to replace a portion of window.location with a randomly generated number?如何用随机生成的数字替换 window.location 的一部分?
【发布时间】:2015-10-08 23:43:58
【问题描述】:

我正在尝试制作一个简单的游戏,其中选择是一种幻觉。您有 4 个按钮可供选择,北、西、东和南,并且 onclick 我希望每个按钮使用 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 button random window.location


【解决方案1】:

你可以用 + 连接,所以我会亲自这样做。

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

【讨论】:

  • 非常感谢!使用您的代码,加上一点谷歌搜索,我最终得到了 window.location.href 和 * 101,因为 +1 不起作用并且 url 没有在它自己的文件夹中引用。我使用第 0 页作为终点,所有页面都完美运行!
【解决方案2】:

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

所以:

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

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

希望我能帮上忙!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多