我试图在 javascript 中打开多个 url 几秒钟并自动关闭它们。我没有编程背景知识,只有一点点php。我这样做是为了演示一个项目。
我有一个包含一些网址的数组。
var allURL = ["http://google.com", "http://yahoo.com", "http://msn.com"];
现在我想在新窗口/选项卡中一一打开所有网址 10 秒并自动关闭。所以http://google.com打开 10 秒并自动关闭,然后 http://yahoo.com打开。与数组中的所有 url 类似。
您能否指导我如何使用 setInterval 或任何其他方式来实现这一点。
最佳答案
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
关于javascript 使用 setInterval 打开和关闭多个 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10751360/