2012-01-02 61 views
0

几周前,我问过this question如何在图库中预加载图像。当解决方案正常工作时,现在出现的问题是,如果我点击下一步预先加载下三张图像,并且前面只有两个图像,则它会全部运行循环三次,并且Firebug将引发未定义的错误。跟进:预加载图像引发未定义错误

这是代码:

$('#next').bind('click',function(){ 
        var $this   = $(this); 
        var $nextimage  = $('#content img:nth-child('+parseInt(current+2)+')'); 
        var next = $nextimage.next(); 
        for (var i = 0; i < 3; i++) 
        { 
         var img = new Image(); 
         img.src = next.attr("alt"); 
         next = next.next(); 
        } 
        navigate($nextimage,'right'); 

       }); 

如何抓住undefined错误,如果只有2个或1个图像,它应该预装只有那些图像,而不是运行循环的第三或第二次抛出错误?

回答

2
$('#next').bind('click',function(){ 
        var $this   = $(this); 
        var $nextimage  = $('#content img:nth-child('+parseInt(current+2)+')'); 
        var next = $nextimage.next(); 
        for (var i = 0; i < 3; i++) 
        { 
         if (!next.length) break; // This line stops your loop if there isn't any next 
         var img = new Image(); 
         img.src = next.attr("alt"); 
         next = next.next(); 
        } 
        navigate($nextimage,'right'); 

       }); 

编辑:

也许你有下一个元素在DOM,但不与属性“ALT”:

$('#next').bind('click',function() { 

    var $this = $(this), 
     $nextimage = $('#content img:nth-child('+parseInt(current+2)+')'), 
     $next = $nextimage.next(); 

    for (var i = 0; i < 3; i++) { 
     if (!$next.length) break; // This line stops your loop if there isn't any next 
     var img = new Image(); 
     img.src = next.attr("alt"); 
     $next = $next.next("[alt]"); // Only takes elements with the alt attribute. 
    } 

    navigate($nextimage, 'right'); 
}); 
+0

我不知道为什么,但它仍然被扔未定义的错误。 Chrome调试器在此行显示:'img.src = next.attr(“alt”);' – input 2012-01-02 17:30:05