创建随机重定向按钮

问题描述 投票:0回答:2

我有以下代码,我想使用一个大的,居中对齐的按钮,将访问者的网站随机重定向到一个网址之一:

<html>
<head>
<script type="text/javascript">
<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "http://www.google.com/";
links[1] = "http://www.bing.com/";
links[2] = "http://www.yahoo.com/";
links[3] = "http://www.apple.com/";

function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}
//-->
</script>
</head>
<body onload="openLink();">
</body>
</html>

我应该如何调整上述代码来实现这一目标?谢谢你的帮助。

javascript html url redirect
2个回答
0
投票

试试这个

<html>
<head>
</head>
<body>
<script>

let links = []; // don't use new Array() anymore
links[0] = "http://www.google.com/";
links[1] = "http://www.bing.com/";
links[2] = "http://www.yahoo.com/";
links[3] = "http://www.apple.com/";
function openLink() {
  var i = ~~(Math.random() * links.length);
  window.location.href = links[i]; // if must be 'parent' leave as 'parent'
  return false;
}
openLink(); // you can also possibly use window.onload = openLink();

</script>
</body>
</html>
Edit: Snippet doesn't work quite as well as it should. Try putting this in a test environment. I opened a blank tab and did a test using Inspect Element's console and it worked.

0
投票

试试这个代码

    <html>
<head>
<script type="text/javascript">
<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "http://www.google.com/";
links[1] = "http://www.bing.com/";
links[2] = "http://www.yahoo.com/";
links[3] = "http://www.apple.com/";

function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}
//-->
</script>
<style>
.btn {
    height:50px;
    width:200px;
    background:#125288;
    color:#fff;
    font-size:18px;
}
</style>
</head>
<body>
</body>
<center>
<button onclick="openLink();" class='btn'>Try to Click</button>
</center>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.