开发者

Dynamically add images jquery

开发者 https://www.devze.com 2023-04-01 14:51 出处:网络
I have an array of images and then I i开发者_StackOverflow社区terate through each using $.each but I can\'t get the images to show on the page, it ends up with nothing getting showed.

I have an array of images and then I i开发者_StackOverflow社区terate through each using $.each but I can't get the images to show on the page, it ends up with nothing getting showed.

<ul id="imagesList">
  <li>No images found</li>
</ul>

$(function(){
            //load image array
            var images = {'image1':'assets/img/linkedin_30px.png','image2':'assets/img/twitter_30px.png'};
            $.each(images, function(){
               $('#imagesList').appendTo('<li>' + this + '</li>'); 
            });
        });


You are using appendTo instead of append. Use append:

$.each(images, function(){
    $('#imagesList').append('<li><img src="' + this + '" /></li>'); 
});

Or, if you insist on using appendTo:

$.each(images, function(){
    $('<li><img src="' + this + '" /></li>').appendTo('#imagesList'); 
});

If you want to show a loader while the image is loading, use this:

var $list = $('#imagesList');

$.each(images, function(i, src) {
    var $li = $('<li class="loading">').appendTo($list);

    $('<img>').appendTo($li).one('load', function() {
        $li.removeClass('loading');
    }).attr('src', src);
});

Here's the fiddle: http://jsfiddle.net/fyar1u7a/1/


There is little issue with your appendTo function. You are using it in wrong way.

Please try below code..

<ul id="imagesList">
  <li>No images found</li>
</ul>
$(function(){
            //load image array
            var images = {'image1':'assets/img/linkedin_30px.png','image2':'assets/img/twitter_30px.png'};
            $.each(images, function(){
               $('<li>' + this + '</li>').appendTo('#imagesList'); 
            });
        });
0

精彩评论

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

关注公众号