我正在尝试编写一个单击缩略图时用ajax加载多个图像的代码。 load方法包含在for循环中,因为图像被命名为my-image-1,my-image-2等。我想通过增加i来加载图像,并退出循环一次/ my-image- i.jpg不存在,产生错误。
function load_slides(i) {
console.log(i);
var url = "some-url.jpg";
var img = $('<img />').attr('src', url).load(function(response, status, xhr) {
if (status == "error") {
console.log("Error loading");
return false;
}
});
}
//code below is triggered upon clicking the thumbnail
for (var i = 1;; i++) {
if (!load_slides(i)) break;
else {
load_slides(i);
}
}
使用上面的代码,我从来没有看到错误消息,并且循环永远不会停止执行,它甚至不应该以错误的url开头:/
在此先感谢您的帮助,我一直试图解决这个问题
答案 0 :(得分:0)
<强>更新强>
您可以使用此功能检查existence
之类的file
,
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status==404;
}
for (var i = 1;; i++) {
// if UrlExists will return true then break, not found image
url='my-image-'+i+'.jpg';
if (UrlExists(url)) break;
else {
load_slides(i);//load image function calling
}
}
来自How do I check if file exists in jQuery or JavaScript?
的来源<强>旧强>
function load_slides(i) {
console.log(i);
var my_status=true;
var url = "some-url.jpg";
var img = $('<img />').attr('src', url).load(function(response, status, xhr) {
if (status == "error") {
console.log("Error loading");
my_status=false;
}
});
return my_status;// return mystatus from here to check;
}
//code below is triggered upon clicking the thumbnail
for (var i = 1;; i++) {
// if my_status will return false then break
if (!load_slides(i)) break;
else {
load_slides(i);
}
}