循环弹出混乱

时间:2015-12-06 11:43:25

标签: javascript loops

有人可以告诉我如何让我的网址正确地循环到我创建的window.open中吗?我想知道循环是否是根据我的setInterval使每个网址轮换的正确答案?如果是,我想知道循环是否需要在var rotate = []{for (var i = 0; i < urls.length; i++)};下。

var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
var rotate = 0;
function goRandom()
{
    var newwin = window.open(
        urls[ rotate ],
        "POPUP",
        "height=400,width=600,scrollbars=yes"
    );
}
var loop = setInterval(goRandom, 5000);

3 个答案:

答案 0 :(得分:0)

只需更改

urls[ rotate ],

urls[ (rotate++) % urls.length ],

索引在每次迭代时递增,% urls.length(%用于获取除法后的余数,因此它确保结果永远不会超出数组大小)。你可以try it here(记得允许弹出窗口)。

答案 1 :(得分:0)

您没有更新rotate ..

的值

尝试这样做

<script type="text/javascript">
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
var rotate = 0;

function goRandom( )
{
    rotate= (rotate+1) % urls.length;
    var newwin = window.open(

                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );
}
    var loop= setInterval(goRandom, 5000);
</script>

答案 2 :(得分:0)

虽然其他答案在技术上是正确的,但如果您刚刚开始使用js,那么这是一个简单的版本,%可能会令人困惑。

// setup urls
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];

// rotate is a global variable so can be accessed anywhere
var rotate = 0;

function goRandom( )
{
    var newwin = window.open(
                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );

    // move to the next array position
    rotate++;

    // Check if at the end of the array and move back to the beginning
    if (rotate >= urls.length)
        rotate = 0;
}


// Keep going indefinitely
setInterval(goRandom, 5000);

现在,您的函数被称为goRandom(),而goSequence()(或goNext()),所以您可以更改此函数而无需任何形式的循环来选择随机网址(尽管您的循环var被称为'rotate',所以也许不是你想要的。)

// setup urls (global so accessed from anywhere)
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];

function goRandom( )
{
    // get a random url
    var rotate = Math.floor(Math.random() * (urls.length - 1));

    var newwin = window.open(
                                     urls[ rotate ],
                                     "POPUP",
                                     "height=400,width=600,scrollbars=yes"                          );
}


// Keep going indefinitely
setInterval(goRandom, 5000);