我通过jQuery $.ajax加载图像路径,在显示图像之前,我想检查它是否存在。我可以使用图像的load/ready事件或类似的方法来确定文件路径是否有效吗?
由于.myimage设置为display:none,我希望做一些类似以下的事情:
$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
$(this).show();
});
有没有类似的东西是可能的?
我通过jQuery $.ajax加载图像路径,在显示图像之前,我想检查它是否存在。我可以使用图像的load/ready事件或类似的方法来确定文件路径是否有效吗?
由于.myimage设置为display:none,我希望做一些类似以下的事情:
$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
$(this).show();
});
有没有类似的东西是可能的?
好的,你可以绑定.error()
处理程序...
更新: 在jQuery 3.0及更高版本中:
$(".myimage").on("error", function() {
$(this).hide();
});
注意:.error()
在jQuery 1.8中已被弃用,且在3.0中已被移除,但在旧版本中仍可使用以下方法:
$(".myimage").error(function(){
$(this).hide();
});
嗯,你的代码已经可以使用load事件了。
$(".myimage").load(function() {
$(this).show();
});
问题在于如果禁用了JavaScript,图片将永远不会显示...
尝试:
function urlExists(testUrl) {
var http = jQuery.ajax({
type:"HEAD",
url: testUrl,
async: false
})
return http.status;
// this will return 200 on success, and 0 or negative value on error
}
那么使用if(urlExists('urlToImgOrAnything') == 200) {
// success
}
else {
// error
}
虽然这是一篇旧帖,但我认为它可以改进。我注意到原帖的问题是间歇性的,可能是由于同时加载图像和错误检查导致的。最好先让图像加载,然后再检查错误:
$(".myimage").attr("src", imagePath).error(function() {
// do something
});
既然您已经在进行AJAX请求,我建议将这个任务转移到支持您的AJAX的服务器端应用程序上。从服务器端检查文件是否存在非常简单,您可以在发送回来的数据中设置变量以指定结果。
.load()
不是一个 ajax.... 参考链接:http://api.jquery.com/load-event/ - Reigel Gallarde$("img")
.error(function(){
$(this).hide();
})
.attr("src", "image.png");
为了捕获事件,您需要在尝试加载图像之前附加错误处理程序。
这是我自己做的:
$.get( 'url/image', function(res){
//Sometimes has a redirect to not found url
//Or just detect first the content result and get the a keyword for 'indexof'
if ( res.indexOf( 'DOCTYPE' ) !== -1 ) {
//not exists
} else {
//exists
}
});