我想使用jquery检查图像是否存在.
例如,如何检查此图像是否存在
http://www.google.com/images/srpr/nav_logo14.png
Run Code Online (Sandbox Code Playgroud)
支票必须给我200或状态确定
--------------编辑-------------------
var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;
if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }
Run Code Online (Sandbox Code Playgroud)
谢谢让
Sar*_*raz 77
使用这样的error处理程序:
$('#image_id').error(function() {
alert('Image does not exist !!');
});
Run Code Online (Sandbox Code Playgroud)
如果无法加载图像(例如,因为它不在提供的URL中),则会显示警报:
更新:
我认为使用:
$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});
Run Code Online (Sandbox Code Playgroud)
足以检查404.
更多读物:
更新2:
你的代码应该是这样的:
$(this).error(function() {
alert('Image does not exist !!');
});
Run Code Online (Sandbox Code Playgroud)
不需要这些行,也不会检查远程文件是否存在:
var imgcheck = imgsrc.width;
if (imgcheck==0) {
alert("You have a zero size image");
} else {
//execute the rest of code here
}
Run Code Online (Sandbox Code Playgroud)
Hel*_*mut 34
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function(){
//do something depressing
},
success: function(){
//do something cheerful :)
}
});
Run Code Online (Sandbox Code Playgroud)
来自:http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
kie*_*iev 12
如果它不存在加载默认图像或句柄错误
$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
if (status == "error")
$(this).attr('src', 'images/DEFAULT.JPG');
else
$(this).attr('src', imgurl);
});
Run Code Online (Sandbox Code Playgroud)
$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});
Run Code Online (Sandbox Code Playgroud)
$.fn.safeUrl=function(args){
var that=this;
if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
return that;
}else{
$.ajax({
url:args.wanted,
type:'HEAD',
error:
function(){
$(that).attr('src',args.rm)
},
success:
function(){
$(that).attr('src',args.wanted)
$(that).attr('data-safeurl','found');
}
});
}
return that;
};
Run Code Online (Sandbox Code Playgroud)
注意:rm这里指风险管理。
$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
Run Code Online (Sandbox Code Playgroud)
' http://example/1.png':如果不存在' http://example/2.png'
' http://example/2.png':如果不存在' http://example/3.png'
| 归档时间: |
|
| 查看次数: |
121651 次 |
| 最近记录: |