html 我如何打开一个随机的网址从一个列表的网址在一个新的时间,每次它被点击?

p1tboqfb  于 2022-12-09  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一些代码,可以让我打开一个随机网站从一个网站列表,但我想打开每一个在一个新的标签,我怎么做?

您可能需要的信息

该代码

<html>
    <button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else!    </button>

    <script type="text/javascript">

    var randomLink = function () {

        // first create an array of links
        var links = [
            "bbc.com",
            "google.com",
            "youtube.com",
        "facebook.com"
        ];

        // then work out the maximum random number size
        // by counting the number of links in the array
        var max = (links.length)

        // now generate a random number
        var randomNumber = Math.floor(Math.random()*max);

        // use that random number to retrieve a link from the array
        var link = links[randomNumber];

        // change the location of the window object
        window.location = "http://" + link;

        // Opens a new tab.
        function OpenInNewTab(url) {
        var win = window.open(url, '_blank');
         win.focus();
}
    }
    </script>
</html>

我试着在两个不同的点上做这个动作,希望你的输入能帮助纠正这个问题。
位置1

<button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else!

地点二

// Opens a new tab.
function OpenInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();

以下网址是代码当前的外观和功能。

gajydyqb

gajydyqb1#

你写的代码是错误的,因为你改变了当前窗口的地址(通过window.location=...行,和其他问题...但在这里:

Working example fiddle的第一个字符

非常相似,和作品。

代码

HTML格式

<button onclick="openStuff();">Click here to go somewhere else!</button>

JS编号

// the used links
var links = [
    "bbc.com",
    "google.com",
    "youtube.com",
    "facebook.com"];

openStuff = function () {
    // get a random number between 0 and the number of links
    var randIdx = Math.random() * links.length;
    // round it, so it can be used as array index
    randIdx = parseInt(randIdx, 10);
    // construct the link to be opened
    var link = 'http://' + links[randIdx];
    // open it in a new window / tab (depends on browser setting)
    window.open(link);
};
l2osamch

l2osamch2#

根据Matyas的回答,我更新了该示例,使其在strict模式下工作。Working Example on Codepen
编号
HTML格式

<button id="open-link">Click here to go somewhere else!</button>

JS的编号

"use strict";

// the used links
const links = ["bbc.com", "google.com", "youtube.com", "facebook.com"];

const openLink = function (links) {
  // get a random number between 0 and the number of links
  // and round it, so it can be used as array index
  const randIdx = parseInt(Math.random() * links.length, 10);
  // construct the link to be opened
  const link = "https://" + links[randIdx];
  // open it in a new window or tab (depends on browser setting)
  window.open(link);
};

window.onload = function () {
  document.getElementById("open-link").onclick = () => openLink(links);
};

相关问题