jQuery jquery动态添加图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7230579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:34:28  来源:igfitidea点击:

Dynamically add images jquery

jquerydynamic

提问by Tsundoku

I have an array of images and then I iterate through each using $.each but I can't get the images to show on the page, it ends up with nothing getting showed.

我有一组图像,然后我使用 $.each 遍历每个图像,但是我无法让图像显示在页面上,最终没有显示任何内容。

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

回答by Joseph Silber

You are using appendToinstead of append. Use append:

您正在使用appendTo而不是append. 使用append

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

Or, if you insist on using appendTo:

或者,如果您坚持使用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/

这是小提琴:http: //jsfiddle.net/fyar1u7a/1/

回答by Pavan Agarwal

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

您的 appendTo 函数没有什么问题。你以错误的方式使用它。

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