2013-02-22 42 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