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:
- Save
images.length
, otherwise this will be computed at every pass through the loop - No need to explicitly test against
true
orfalse
- No need to use
document.createElement
and then jQuery-ify it. - No need to use
.attr()
(seejQuery(html, props)
)
精彩评论