2013-01-09 2 views
0

jQuery를 사용하여 이미지와 텍스트를 내 문서에 삽입하고 있지만 이미지가 실제로 존재하면 이미지를 포함하고 싶습니다 (이미지 경로는 변수, img_url, 기존 이미지를 참조 할 수도 있고 참조하지 않을 수도 있음). 여기 jQuery : 이미지가있을 경우에만 삽입하십시오.

내 코드의 단순화 된 버전입니다 : 나 이미지의 존재 여부에 따라 올바른 경고를받을 수 있나요 동안

var text = data.html, 
    image = '<img class="myimage" src="' + img_url + '" />'; 

var imageTest = $("<img>"); 
    imageTest.attr('src', img_url).load(function() { 
     alert("image exists"); 
    }).error(function() { 
     alert("image doesn't exist"); 
     imageTest.remove(); 
    }); 

if (imageTest.length) { 
    $("#content").html(image + text); 
} else { 
    $("#content").html(text); 
} 

imageTest.length 항상 1로 평가, 그래서 나는 아직도 항상 이미지와 끝까지 깨진 경우에도 #content에 삽입됩니다.

어디로 잘못 가고 있습니까? imageTest.remove() 이미지 요소가로드되지 않으면 삭제해야하므로 길이는 0이 아니어야합니다.

+0

"기존 이미지를"다시 한

$('#example').append(imageTest); 

으로 다시 연결 수 있을까? 정의가 필요합니다. 나는 두 가지 해석을 생각할 수있다. –

답변

1

난 당신이 아마 [개체 개체] ... 당신은 대신 추가 사용할 수 있습니다 얻을 것이다 발견하지만이

var imageTest = $("<img>"); 
imageTest.attr('src', img_url).load(function() { 
    alert("image exists"); 
    $("#content").html(image + text); // <-- move it here - if loaded successfully add it 
}).error(function() { 
    alert("image doesn't exist"); 
    imageTest.remove(); // <-- don't need this since it's not even in the dom 
    $("#content").html(text); // <-- move it here - if failed then just add text 
}); 

을하거나 문자열

var text = "test text"; 
var imageTest = $("<img>"); 
imageTest.attr('src', 'http://dummyimage.com/300').load(function() { 
    alert("image exists"); 
    $("#content").empty().append(imageTest).append(text); // <-- move it here - if loaded successfully add it 
}).error(function() { 
    alert("image doesn't exist"); 
    imageTest.remove(); // <-- don't need this since it's not even in the dom 
    $("#content").html(text); // <-- move it here - if failed then just add text 
}); 
으로 개체를 변환해야합니다

FIDDLE

또는 문자열

로 변환 등 53,210

FIDDLE

-1

항상 존재하는 이유는 실제로 이미지가 서버에 있지 않으면 404를 반환한다는 것입니다. 실제로는 404가 존재합니다. JQuery는 서버 측에서 모든 것을 감지 할 수 없다. PHP 또는 PHP가 존재하는지 여부를 감지하는 데 사용할 서버 측 언어를 사용해야합니다.

+0

서버가 404를 보낸 경우 jQuery가 올바르게 감지합니다. –

1

는 JQuery와 doumentation에 따르면 .remove()는 단지 DOM 밖으로 유사한 요소를 제거하지만 객체 자체는 여전히 존재한다. 당신은 당신은 imageTest에게

imageTest = [];