2013-01-09 21 views
0

我使用jQuery插入圖像和文本blob到我的文檔,但我只想包括圖像,如果它實際存在(圖像路徑是一個變量,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

「現有圖像」?需要定義。我可以想到兩種解釋。 –

回答

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 
}); 

雖然我注意到,你可能會得到[Object對象]。您可以使用附加代替或你將不得不將對象轉換成字符串

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

還是因爲它轉換成字符串

var text = "test text"; 
var imageTest = $("<img>"); 
imageTest.attr('src', 'http://dummyimage.com/300').load(function() { 
    alert("image exists"); 
    var img = $('<div/>').append(imageTest.clone()).html(); // get it as a String 
    $("#content").html(img + 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

-1

它會一直存在的原因是,如果圖像沒有駐留在服務器上,404實際上存在,它將返回404。 JQuery無法在服務器端檢測到事物。您應該使用PHP或任何您正在使用的服務器端語言來檢測它是否存在。

+0

如果服務器發送了404,jQuery的確檢測正確 –

1

根據jquery的doumentation,卸下襬臂()只刪除匹配元素出DOM的,但物體本身仍然存在。你可以用

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

重新安裝它,你必須重新imageTest

imageTest = []; 
相關問題