开发者

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: imageC开发者_StackOverflow社区lass}).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.


$.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))
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜