跟进:预加载图像会引发未定义的错误

时间:2012-01-02 16:50:14

标签: javascript jquery image preload

几个星期前我曾问过this question如何在图库中预加载图像。虽然该解决方案有效,但现在出现的问题是,如果我单击Next来预加载接下来的三个图像并且前面只有两个图像,它会三次运行循环并且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个图像,它应该仅预加载那些图像而不是第三次或第二次运行循环以抛出错误?

1 个答案:

答案 0 :(得分: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' );
});