Dynamically add jquery images

I have an array of images, and then I repeat each of them using $ .each, but I canโ€™t get the images that will be displayed on the page, and in the end nothing will work.

<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>'); }); }); 
+6
source share
2 answers

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 the bootloader during image 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/

+14
source

The problem with your appendTo function is small. You are using it incorrectly.

Please try the code below.

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

Source: https://habr.com/ru/post/896124/


All Articles