0

我试图在 javascript 中打开多个 url 几秒钟并自动关闭它们。我没有编程方面的背景知识,只是一点点php。我这样做是为了演示一个项目。

我有一个带有一些网址的数组。

var allURL = ["http://google.com", "http://yahoo.com", "http://msn.com"];

现在我想在新窗口/标签中一一打开所有 url 10 秒并自动关闭。所以http://google.com打开 10 秒并自动关闭,然后http://yahoo.com打开。与数组中的所有 url 类似。

您能否指导我如何使用 setInterval 或任何其他方式来实现。

4

1 回答 1

3
var allURL = ["http://google.com","http://yahoo.com","http://msn.com"];

function showUrl(index) {
    index = index || 0;

    // are there any urls to show?
    // is the given index valid?
    if (allURL.length === 0 || index < 0 || index >= allURL.length) {
        return;
    }

    // open the url
    var popup = window.open(allURL[index]);

    // set a timer which closes the popup after 10 seconds and opens the next url by calling 'showUrl' with the next index
    setTimeout(function() {
        popup.close();
        showUrl(index + 1);
    }, 10000);
}

// To start the "diashow" call 'showUrl' without an index or if you want to start at a pre-defined url with the corresponding index
showUrl();    // starts with the first url
于 2012-05-25T09:08:45.753 回答