点击一个链接,随机跳转到其他网址的JS实现方法

问题遇到的现象和发生背景

不懂代码,希望在WordPress文章内,点击一个链接,随机跳转到不同的网址,在网上找到下面代码,前段时间测试,还是有效的,但是现在打算使用时,发现可以在新标签页打开,但是空白页,并没有随机打开其中的网址,请问下面代码有问题吗?另外不想暴露自己的网站,所以希望加上 rel="nofollow noopener noreferrer" 这段代码,应该加在哪个位置?

请修改下面或提供其他源代码,非常感谢!

 
 <script language="javascript">
   function test(){
     var url=new Array();
     url[0]="http://www.baidu.com";
     url[1]="http://www.csdn.net";
     url[2]="http://bbs.voc.com.cn";
     var ints=parseInt(Math.random()*(url.length));
     window.open(url[ints]);//本窗口打开     
     //window.location=url[ints];//新窗口打开 
    }
 
 script>
<a href="javascript:test()">testa>

  1. 通过href跳转
<html>
<head>
    <script type="text/javascript">

        function openLink(e) {
            var url = new Array();
            url[0] = "http://www.baidu.com";
            url[1] = "http://www.csdn.net";
            url[2] = "http://bbs.voc.com.cn";
            var ints = parseInt(Math.random() * (url.length));
            e.href = url[ints];
            return false;
        }
    </script>
</head>
<body>
</body>
<a href="#" onclick="openLink(this)" target="_blank" rel="nofollow noopener noreferrer">Try to Click</a>
</html>
  1. 通过window.open跳转,但是指支持部分属性
        window.open(url[ints], null, 'noopener=yes,noreferrer=yes');

rel="nofollow noopener noreferrer" 应该加在 a 标签的末尾,如下:

<a href="javascript:test()" rel="nofollow noopener noreferrer">test</a>

一种可行的方法是:

创建一个数组,用于存储可以随机跳转的网址。

为链接添加点击事件处理函数,在函数中执行以下步骤:

随机生成一个数字,并使用该数字作为数组的索引,获取对应的网址。

使用JavaScript的location.href属性跳转到该网址。

例如:

// 创建网址数组
var urls = ["http://www.example.com/1", "http://www.example.com/2", "http://www.example.com/3"];

// 为链接添加点击事件处理函数
document.getElementById("link").addEventListener("click", function() {
  // 随机生成一个数字
  var index = Math.floor(Math.random() * urls.length);
  // 跳转到对应的网址
  location.href = urls[index];
});