我有以下ajax调用,它可以获取相对用户的所有图像:
$.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');
}
}
});
正如您在最后看到的那样,我将图像附加到ID:
$(document.createElement("img")).attr({ src: imageUrl, filename: fileName, imageKey: idImage , class: imageClass}).appendTo('#userImagesContainer');
相反,我想将它附加到列表中,每个图像都放在li:
上<ul>
<li>img01</li>
<li>img02</li>
[etc...]
</ul>
我很困惑,我需要你的帮助......在此先感谢。
答案 0 :(得分:1)
$.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');
}
});
代码清理:
images.length
,否则将在每次通过循环时计算true
或false
document.createElement
然后使用jQuery-ify it。.attr()
(请参阅jQuery(html, props)
)