gpt4 book ai didi

javascript - 跟进: Preloading images throws undefined error

转载 作者:行者123 更新时间:2023-12-02 19:55:26 26 4
gpt4 key购买 nike

我问过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');

});

如何捕获未定义错误,如果只有2个或1个图像,它应该只预加载这些图像,而不是第三次或第二次运行循环来抛出错误?

最佳答案

$('#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' );
});

关于javascript - 跟进: Preloading images throws undefined error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com