2013-02-22 72 views
-1

我用大量的圖片時加載到DOM如若跌破

html += '<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'">'; 

的數據來自一個Ajax調用,並在for循環中,每個圖像在頁面上哪裏來交換圖像。我有兩個圖像裁判的情況下,一個被打破image.previewimage.preview2(我用兩成image.preview是本地的,但在錯誤的情況下再image.preview2是原始圖像)

如果image.preview壞我想切換到image.preview2

我在嘗試以下但不知道放置在哪裏?

$('img').on('error', function() { this.src = image.preview2; }); 

我的html +=受審,中,後但沒有中間似乎工作 - 任何想法?

+0

閱讀評論直接你上面。 – 2013-02-22 10:00:00

回答

-2

想通了最簡單的WASY做到這一點是內聯:

html += '<img src....onerror="this.onerror=null;this.src=\''+image.preview2+'\';">'; 
0

你可以這樣做:

var newImg = $('<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'">'); 
newImg.on('error', function() { this.src = image.preview2; }); 

and then 

<the html container>.append(newImg); 

這將確保圖像中有所有設置之前,它被添加到DOM和牽強。

1

如果preview2圖像源是每個圖像不同,那麼我建議for循環這樣的範圍內做:

for(n in images) { 
    var image = images[n]; 

    // create jQuery object (is not in the DOM jet) 
    $img = $('<img title="View larger image" alt="' + image.item_title + '" height="' + image.display_height + '" width="' + image.display_width + '">'); 

    // is there an preview src? 
    if(typeof image.preview == 'Undefined' || image.preview == '') { //nopes 
     $img.attr('src', image.preview2); 
    } else { //yes 
     $img.attr('src', image.preview); 
    } 

    // add the image to the DOM 
    $('#id_of_element').append($img); 
} 
+1

更好的解決方案,我贊同這個:) – Timmetje 2013-02-22 09:16:03

+0

這是檢查url引用是否存在圖像,而不是如果圖像實際存在雖然,正確嗎?還是我讀錯了? – 2013-02-22 09:24:27

+0

它檢查是否設置了圖像的'preview'屬性。所以它不會檢查圖像是否存在。 – 2013-02-22 09:29:17

0

example:

function setDefaultImage(img) 
{ 
    img.src = "images/candidates/human.jpg"; 
} 

希望這會幫助你。 。

in your scenario..

html += '<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'" onerror="'setDefaultImage(this)'">'; 

function setDefaultImage(img) 
    { 
     img.src = "image.preview2"; 
    } 
+0

這是關閉,但我得到的錯誤NetworkError:404未找到 - http://myurl.com/pages/image.preview2 - 它沒有引入適當的參考 – 2013-02-22 09:19:20

+0

可能會出錯的路徑.. – sasi 2013-02-22 09:39:08