我喜欢click()
在多个文件下载中的a
元素上执行事件for loop
仅适用于有限数量的文件(在我的情况下为 10 个文件)。可以解释这种对我有意义的行为的唯一原因是click()
事件执行的下载速度/间隔。
我发现,如果我减慢click()
事件的执行速度,那么我将能够下载所有文件。
这是对我有用的解决方案。
var urls = [
'http://example.com/file1',
'http://example.com/file2',
'http://example.com/file3'
]
var interval = setInterval(download, 300, urls);
function download(urls) {
var url = urls.pop();
var a = document.createElement("a");
a.setAttribute('href', url);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
if (urls.length == 0) {
clearInterval(interval);
}
}
我click()
每 300 毫秒执行一次下载事件。当没有更多的要下载的文件urls.length == 0
,然后,我执行clearInterval
的interval
功能停止下载。