주어진 url로 이미지가 존재하는지 확인하는 방법은?
jquery를 이용해서 이미지가 존재하는지 확인하고 싶습니다.
예를 들어 이 이미지가 있는지 확인하는 방법
http://www.google.com/images/srpr/nav_logo14.png
수표는 나에게 200 또는 상태 ok를 주어야 합니다.
----------------edited-------------------------------------------
var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;
if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }
Thanks Jean
핸들러를 다음과 같이 사용합니다.
$('#image_id').error(function() {
alert('Image does not exist !!');
});
이미지를 로드할 수 없는 경우(예: 제공된 URL에 존재하지 않기 때문에) 경고가 표시됩니다.
업데이트:
사용 방법:
$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});
404를 확인하기에 충분합니다.
추가 판독값:
- http://www.jibbering.com/2002/4/httprequest.html
- http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/
업데이트 2:
코드는 다음과 같습니다.
$(this).error(function() {
alert('Image does not exist !!');
});
이러한 줄이 필요 없으며 원격 파일이 존재하는지 여부를 확인할 수도 없습니다.
var imgcheck = imgsrc.width;
if (imgcheck==0) {
alert("You have a zero size image");
} else {
//execute the rest of code here
}
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function(){
//do something depressing
},
success: function(){
//do something cheerful :)
}
});
출처: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
없는 경우 기본 이미지 로드 또는 핸들 오류
$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
if (status == "error")
$(this).attr('src', 'images/DEFAULT.JPG');
else
$(this).attr('src', imgurl);
});
유즈케이스
$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});
API :
$.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;
};
참고:rm
위험 관리를 의미합니다.
다른 사용 사례:
$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
'
http://example/1.png
' 존재하지 않는 경우 'http://example/2.png
''
http://example/2.png
' 존재하지 않는 경우 'http://example/3.png
'
여기서부터:
// when the DOM is ready
$(function () {
var img = new Image();
// wrap our new image in jQuery, then:
$(img)
// once the image has loaded, execute this code
.load(function () {
// set the image hidden by default
$(this).hide();
// with the holding div #loader, apply:
$('#loader')
// remove the loading class (so no background spinner),
.removeClass('loading')
// then insert our image
.append(this);
// fade our image in to create a nice effect
$(this).fadeIn();
})
// if there was an error loading the image, react accordingly
.error(function () {
// notify the user that the image could not be loaded
})
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});
jQuery 3.0 제거 .error
. 정확한 구문은 지금입니다.
$(this).on('error', function(){
console.log('Image does not exist: ' + this.id);
});
이미지 존재 확인으로 게으른 로딩을 처리하기 위해 jQuery-에서 이 내용을 따라 했습니다.
$('[data-src]').each(function() {
var $image_place_holder_element = $(this);
var image_url = $(this).data('src');
$("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
if (!(status == "error")) {
$image_place_holder_element.removeClass('image-placeholder');
$image_place_holder_element.attr('src', image_url);
}
}).remove();
});
이유: 사용하는 경우$image_place_holder_element.load()
방법은 요소에 대한 응답을 추가하는 것이기 때문에 임의의 div와 그것을 제거하는 것이 좋은 해결책으로 보입니다.URL 확인과 함께 게으른 로딩을 구현하려는 누군가에게 효과가 있기를 바랍니다.
언급URL : https://stackoverflow.com/questions/3381663/how-to-check-if-image-exists-with-given-url
'source' 카테고리의 다른 글
두 열 A,B를 기준으로 데이터 프레임에서 중복 제거, 다른 열 C에 최대값이 있는 행 유지 (0) | 2023.10.11 |
---|---|
Node.js와 함께 밑줄 모듈 사용 (0) | 2023.10.11 |
git receive 전 후크가 heroku와 함께 감소했습니다. (0) | 2023.10.11 |
배열의 열에 대해 반복하는 방법은 무엇입니까? (0) | 2023.10.11 |
SASS - 여러 파일에 걸쳐 변수 사용 (0) | 2023.10.11 |