如何在每次点击时在新的时间段打开网址列表中的随机网址?

时间:2014-07-01 11:40:45

标签: javascript html html5

我有一些代码允许我从网站列表中打开一个随机网站,但我想在新标签中打开每个网站,我该怎么做?

您可能需要的信息

代码

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

位置2

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

以下网址是代码目前的样子和行为。

*编辑:我所做的唯一改变是网站。他们更多关于现场演示。

1 个答案:

答案 0 :(得分:2)

您编写的代码是错误的,因为您更改了当前窗口的地址(通过行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);
};