我试图为每个div附加两个不同的JSON项目。我在循环json之前清空div然后追加对象。
但我需要每个div附加两个,每个项目必须不同。 例如。 div1有img1& img2,div2有img3& img4等。
这是我得到的结果 -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
</div>
但这是我需要的结果 -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
</div>
<div>
<img class="img3">
<img class="img4">
</div>
<div>
<img class="img5">
<img class="img6">
</div>
</div>
$.each(data.carImages, function(i){
counter++;
imgLink = data.carImages[i].imgLink;
console.log(counter);
$('.gallery-slider').append('<div><img src="' + imgLink + '" class="gallery-img" data-tag="' + i + '"></div>');
$('.gallery-sub-slider').append('<div class="sub-gallery-item" data-index="' + i + '"></div>');
$('.gallery-sub-slider div').append('<img src="' + imgLink + '" class="sub-gallery-img" data-tag="1"><img src="' + imgLink + '" class="sub-gallery-img">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
答案 0 :(得分:1)
您可以考虑首先计算您需要的div数量,而不是遍历每个data.carImage:
var divCount = Math.ceil(data.carImages.length / 2)
循环遍历:
for (var i = 0; i < divCount; i++) {
var firstImgIndex = i*2;
var secondImgIndex = firstImgIndex + 1;
var firstImg = data.carImages[firstImgIndex];
var secondImg = data.carImages[secondImgIndex];
// create your div now, with your first and second img, but you might have to check that secondImg !== null or undefined
}