loop popup confusion

前端 未结 3 1542
悲&欢浪女
悲&欢浪女 2021-01-28 05:59

Can someone tell me how to make my URLs properly loop into the window.open I created? I’m wondering if the loop is the right answer to make each URL rotate based on

3条回答
  •  青春惊慌失措
    2021-01-28 06:50

    While the other answers are technically correct, here's a simplied version if you're just starting out with js, all that % can be confusing.

    // 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);
    

    Now, your function is called goRandom() while this will goSequence() (or goNext()), so you can change this without any form of loop to pick a random url (though your loop var is called 'rotate' so maybe not what you wanted).

    // 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);
    

提交回复
热议问题