我正在使用 ajax 来检查我的图像目录中是否有可用的文件。如果它在那里,我将它附加到我的 html 代码中,并将一个布尔值更改为 true,让用户知道它被找到了。如果它没有找到文件名,我检查它是否是一个 2 部分图像(连接图像名称末尾的数字 1 和 2 并生成 2 个图像)。布尔值也更改为 true,表示找到了图像。尽管如果没有单部分或两部分图像,代码应该只是从 ajax 中出错,将布尔值保留为 false,告诉用户没有图像。
除了在没有图像时通知用户之外,我的逻辑在所有方面都很好。在ajax成功函数中,图像总是追加(无论成功还是错误),但布尔值在成功后永远不会改变。这是我正在运行的代码。
boolean = false //declared globally
function tableSelect(location){
$("#popupPhoto").text("");
var part = $("#table"+location).text().split(" ");
//part[0] always empty
for(var i=1;i<part.length;i++){
//change default value to false
boolean = false;
/* original code
imageExists(part[i]);
//when no file... is found, boolean stays false, causing this if statement to function
if(boolean == false){
alert("No Information for "+imagename+" of "+part[i]);
//displayes image that says "No Information Available"
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/nia.png', "class": 'popphoto', alt: 'NIA' }));
}
*/
//new code
imageExists(part[i]).fail(function () {
alert("No Information for "+imagename+" of "+part[i]);
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/nia.png', "class": 'popphoto', alt: 'NIA' }));
})
}//Displays images in popup
$("#popupPhoto").addClass("ui-popup-active");}
这是检查图像的功能
function imageExists(part){
var url = "images/imagedir/"+part+".png";
$.ajax({
url:url,
type:'HEAD',
error: function()
{
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'1.png', "class": 'popphoto', alt: part.concat("1") }));
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'2.png', "class": 'popphoto', alt: part.concat("2") }));
//boolean = true;
//boolean changes here
},success: function()
{//boolean will not change here
//boolean = true;
$("#popupPhoto").append($("<img>", {src: 'images/imagedir/'+part+'.png', "class": 'popphoto', alt: part }));
}
});
}
我知道这可能是我不了解此功能的详细信息及其工作原理,但是如果有人可以帮助解决此问题或提出更好的方法来解决此问题,那基本上就是我正在寻找的。提前致谢。