【问题标题】:Creating a random redirect button创建一个随机重定向按钮
【发布时间】:2018-08-12 15:15:28
【问题描述】:

我有以下代码,我想将其与一个居中对齐的大按钮一起使用,以将访问者随机重定向到网站的一组 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>

我应该如何调整上面的代码来实现这一点?感谢您的帮助。

【问题讨论】:

  • 应该是window.location.replace("url") 或者window.location = "url"
  • window.location.href 不仅仅是window.location

标签: javascript html url redirect


【解决方案1】:

试试这个

<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>
编辑: Snippet 不能正常工作。尝试将其置于测试环境中。我打开了一个空白选项卡,并使用 Inspect Element 的控制台进行了测试,它工作正常。

【讨论】:

    【解决方案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>
    <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>
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多