我正在尝试编写一些代码来查找网页上的所有链接图像。到目前为止,我能够生成所有链接 (imageLinks) 的数组,但在最终 console.log(linkedImages) 下面的代码中始终显示一个空数组。
我无法理解的是我评论过“这有效/但这不起作用:”
我究竟做错了什么?非常感谢这个有点菜鸟的任何帮助。谢谢!
//Create an array of all the links containing img tags
var imageLinks = $("img").parent("a").map(function () {
var h = $(this).attr("href");
return h;
}).get();
//This correctly shows all the links:
//console.log(imageLinks);
//Declare an array to hold all the linked images
var linkedImages = [];
//Loop through all the links to see if they're images or not
for (var l = 0; l < imageLinks.length; l++) {
var currLink = imageLinks[l];
function myCallback(url, answer) {
if (answer) {
//This works:
console.log(url + ' is an image!');
//But this doesn't work
linkedImages.push(url);
} else {
//alert(url+' is NOT an image!');
}
}
function IsValidImageUrl(url, callback) {
var img = new Image();
img.onerror = function () {
callback(url, false);
}
img.onload = function () {
callback(url, true);
}
img.src = url
}
IsValidImageUrl(currLink, myCallback);
};
//HELP! This always evaluates as just "[]"
console.log(linkedImages);