开发者

Loading a gallery of external images with JQuery

I'm creating a gallery of images pulled in via a twitter image hosting service, and I want to show a loading graphic before they are displayed, but the logic seems to be failing me. I'm trying to do it the following way:

<ul>
    <li>
        <div class="holder loading">
        </div>
    </li>
    <li>
        <div class="holder loading">
        </div>
    </li>
    <li>...</li>
    <li>...</li>
</ul>

Where there "loading" class has an animated spinner set as it's background image.

JQuery:

$('.holder').each(function(){
开发者_JAVA技巧    var imgsrc = 'http://example.com/imgsrc';
var img = new Image();
    $(img).load(function () {
        $(this).hide();
        $(this).parent('.holder').removeClass('loading');
        $(this).parent().append(this);
        $(this).fadeIn();
})
.error(function () {
}).attr('src', imgsrc);
 });

Which isn't working - I'm not sure that the logic is correct and how to access the "holder" from inside the img.load nested function. What would be the best way to build this gallery so that the images display only after they've been loaded?


For starters, you are not quoting the URL here:

var imgsrc = http://example.com/imgsrc;

should be:

var imgsrc = 'http://example.com/imgsrc';

Try this:

$('.holder').each(function(){
    var imgsrc = 'http://example.com/imgsrc';
    var $img = $('<img />', {src: imgsrc});
    $($img).load(function () {
        $(this).hide();
        $(this).parent('.holder').removeClass('loading');
        $(this).parent().append(this);
        $(this).fadeIn();
    });
});

I think the problem was that the load event was bound to an image without any src attribute (I could be wrong, do let me know how it goes :)


So after much confusion and searching, I figured it out - to access the holder from within the nested function, I had to create a holder for it:

$('.holder').each(function(){
   var holder = $(this);
   var imgsrc = 'http://example.com/imgsrc';
   var $img = $('<img />', {src: imgsrc});
   $($img).load(function () {
       $(this).hide();
       holder.removeClass('loading');
       holder.append(this);
       $(this).fadeIn();
   });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜