我的ajax调用返回:(有两个图像,图像数量可能会有所不同)
[{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"},
{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/completionist.png"}]

我可以在我的用户界面中显示图像,如下所示:
if (counter<=0){
$('#imagesofBadges').append('<img src="' + data[0].BadgeImage + '"/>');
$('#imagesofBadges').append('<img src="' + data[1].BadgeImage + '"/>');
counter++;
}
&#13;
问题: 关键是我不想使用两个append语句,因为ajax调用返回的图像的数量可能会有所不同。这将取决于从DB中提取图像的条件。图像是从相同的列名称中提取的&#34; BadgeImage&#34;可以在ajax数据中看到。
我试过的代码:
var $img = $('<img src="' + data[0].BadgeImage + '"/>'); // create the image
$img.addClass('badge-image'); // add the class .badge-image to it
$('#imagesofBadges').append($img); // append it
$('#imagesofBadges .badge-image'); // will fetch all the elements that have the class .badge-image that are inside #imagesofBadges.
&#13;
请帮助。
答案 0 :(得分:1)
使用.each函数
尝试以下代码<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var data = '[{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"}, {"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/completionist.png"},{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/2.png"},{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/3.png"}]';
data = jQuery.parseJSON(data);
$.each(data, function( index, value ) {
var $img = $('<img class="badge-image" src="' + data[index].BadgeImage + '"/>'); // create the image
$('#imagesofBadges').append($img); // append it
});
$('#imagesofBadges .badge-image').each(function () {
alert($(this).attr('src'));
}); // will fetch all the elements that have the class .badge-image that are inside #imagesofBadges.
});
</script>
</head>
<div id="imagesofBadges">
</div>
答案 1 :(得分:1)
实际上,我不明白你的意思。也许你可以尝试一下!
var data = [
{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"},
{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/completionist.png"}];
var dom = data.map(function (value) {
return '<img src="' + value.BadgeImage + '"/>';
})
$('#imagesofBadges').append(dom.join(''));
答案 2 :(得分:0)
试试这个:
$('#imagesofBadges').empty();
$.each(data, function(index, value) {
//Your code
});