簡體   English   中英

創建一個隨機重定向按鈕

[英]Creating a random redirect button

我有以下代碼,我想將其與一個大的,居中對齊的按鈕一起使用,以將訪問者的網站隨機重定向到URL數組之一:

<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>

我應該如何修改以上代碼來實現這一目標? 謝謝你的幫助。

嘗試這個

 <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> 
編輯:代碼段無法正常運行。 嘗試將其放在測試環境中。 我打開了一個空白選項卡,並使用Inspect Element的控制台進行了測試,它可以正常工作。

嘗試到此代碼

    <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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM