Andrea Turri
Andrea Turri

Reputation: 6500

Add images to a list

I have the following ajax call that take all the images of a relative user:

$.ajax({
             type: "POST",
             url: "../../Services/Registration.svc/GetAllImagesUrls",
             data: '{"idImg" : ' + idImg + '}',
             contentType: "application/json",
             dataType: "json",
             success: function (response) {
                 ClearContents();
                 var images = response.d;
                 for (var i = 0; i < images.length; i++) {
                     var imageUrl = images[i].ImageUrl;
                     var isDefault = images[i].IsDefault;
                     var fileName = images[i].FileName;
                     var idImage = images[i].IdImage;
                     var imageClass = 'userImage';
                     if (isDefault == true)
                         imageClass = imageClass + ' defaultImage';
                     $(document.createElement("img")).attr({ src: imageUrl, filename: fileName, imageKey: idImage , class: imageClass}).appendTo('#userImagesContainer');

                 }
             }
         });  

As you can see at the end I append the images to an ID:

$(document.createElement("img")).attr({ src: imageUrl, filename: fileName, imageKey: idImage , class: imageClass}).appendTo('#userImagesContainer');

Instead I would like to append it to a list, each image on a li:

<ul>
    <li>img01</li>
    <li>img02</li>
    [etc...]
</ul>

I'm confused and I need your help... Thanks in advance.

Upvotes: 0

Views: 1498

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

$.ajax({
    type: "POST",
    url: "../../Services/Registration.svc/GetAllImagesUrls",
    data: '{"idImg" : ' + idImg + '}',
    contentType: "application/json",
    dataType: "json",
    success: function(response) {
        ClearContents();
        var images = response.d,
            len = images.length, // 1
            $ul = $('<ul></ul>'),
            $li;
        for (var i = 0; i < len; i++) {
            var imageUrl = images[i].ImageUrl;
            var isDefault = images[i].IsDefault;
            var fileName = images[i].FileName;
            var idImage = images[i].IdImage;
            var imageClass = 'userImage';
            if (isDefault) imageClass = imageClass + ' defaultImage'; // 2
            $('<img></img>', { // 3, 4
                src: imageUrl,
                filename: fileName,
                imageKey: idImage,
                class: imageClass
            }).appendTo($ul);

        }
        $ul.find('img').wrap('<li></li');
        $ul.appendTo('#userImagesContainer');
    }
});

Code cleanup:

  1. Save images.length, otherwise this will be computed at every pass through the loop
  2. No need to explicitly test against true or false
  3. No need to use document.createElement and then jQuery-ify it.
  4. No need to use .attr() (see jQuery(html, props))

Upvotes: 1

Related Questions