我有一個非常簡單的jQuery預加載器,它工作正常(我相信代碼是正確的,但請繼續檢查出來)...
我想要做的是,如果圖像無法下載,請嘗試圖像的其他變體,直到找到一個圖像爲止....只有4種變體可以用路徑中的數字表示。jquery如何遞歸調用圖像預加載器
讓我解釋一下:
成像路徑可能是如下
... /圖片/ 800像素/ image1.jpg
如果一個失敗,然後嘗試
... /圖片/ 350像素/image1.jpg
如果一個失敗,然後嘗試
... /圖片/ 100像素/ image1.jpg
如果一個失敗,再嘗試
... /圖片/ 50像素/ image1.jpg
如果一個失敗,然後嘗試
... /圖片/ 30像素/ image1.jpg
如果你注意到,在性差異在所有這些的變化,是路徑內的數字...這是800,350,100,50,30的數字
現在,在函數load_img(下面)我想使用.error屬性來遞歸調用函數直到它發現一個圖像..
這是最好的方法?有關如何實現這一目標的任何提示或最佳實踐?
在此先感謝
馬爾科
下面的代碼樣本
<div id="zoom-artwork"></div>
<ul class="nav-zoom-artwork">
<li><a href=".../images/800px/image1.jpg">image doesn't exist...</a></li>
<li><a href=".../images/800px/image2.jpg">image 2</a></li>
<li><a href=".../images/800px/image3.jpg">image 3</a></li>
</ul>
...
$('#nav-zoom-artwork a').click(function(e) {
var src = $(this).attr('href');
var alt = $(this).children('img').attr('alt');
load_img(src, alt);
e.preventDefault();
});
// ZOOM artwork
function load_img(src, alt) {
var img = new Image();
$(img).load(function() {
// set the image hidden by default
$(this).hide();
// remove the loading class, then insert the image
$('#zoom-artwork').removeClass('loading').html(this);
// fade in the image to create a nice effect
$(this).fadeIn(400);
})
.error(function() {
alert('try another size... call the function recursively with another path...');
})
.attr({
src:src,
alt:alt
});
}