Reputation: 16764
I developed a Firefox extension where downloads multiple files from a page by triggering on different anchors with different links.
What I did in javascript with jQuery:
var $tr = $("tr");
var downloadLinks = [];
$.each($tr, function() {
var tds = $(this).find("td");
var name = tds.eq(1).find("span");
var text = name.text();
if (text.match(/\.Update\./gi)) {
return true;
}
downloadLinks.push(tds.eq(2).find("a"));
});
if (downloadLinks.length > 0 && confirm("Found " + downloadLinks.length + " items to be downloaded. Download them now ?")) {
for (var i = 0; i < downloadLinks.length; i++) {
var $a = downloadLinks[i];
var url = $a.prop("href");
if (url.indexOf("http") < 0) {
url = windows.location.protocol + "//" + windows.location.host + "/" + $a.prop("href").trim('/');
}
$a.prop("href", url);
setTimeout(function() {
$a.get(0).click();
}, 800 * (i + 1));
}
}
The problem is that only last item is downloaded downloadLinks.length
times. If length is 20 then last item is downloaded 20 times.
Where is my mistake ?
Upvotes: 3
Views: 124
Reputation: 2603
$a is the problem here, when time out is fired $a is equals to the last object read by the loop.
try with:
setTimeout(function(j) {
var $a = downloadLinks[j];
$a.get(0).click();
}, 800 * (i + 1), i);
this should work.
Upvotes: 1