我有一个 URL 数组,需要循环遍历并在新窗口中打开。但是,我需要能够在每个窗口的打开和关闭之间设置超时。换句话说,窗口应该只在设定的时间间隔内保持打开状态,然后移至数组中的下一个 URL。
以下代码打开窗口,但仅关闭第一个窗口。
(function X() {
document.getElementById("target").onclick = function () {
var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var wnd;
for (var i = 0; i < urlList.length; i++) {
wnd = window.open(urlList[i], '', '');
setTimeout(function () {
wnd.close();
}, 2000);
}
};
return true;
}
)();
想法?
最佳答案
您的 for 循环
一次有效地运行所有内容,因此您的代码会同时打开所有窗口,然后您的关闭超时将在 2 秒后全部启动(全部同时)。
数组的每次迭代之间需要有一个超时。
这里有一种方法可以做到这一点:
var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var wnd;
var curIndex = 0; // a var to hold the current index of the current url
function openWindow(){
wnd = window.open(urlList[curIndex], '', '');
setTimeout(function () {
wnd.close(); //close current window
curIndex++; //increment the index
if(curIndex < urlList.length) openWindow(); //open the next window if the array isn't at the end
}, 2000);
}
openWindow();
关于Javascript:遍历 URL 数组并打开,然后按定义的时间间隔关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701987/