gpt4 book ai didi

javascript - 每个 div 添加 2 个 json 对象

转载 作者:行者123 更新时间:2023-11-28 00:53:27 24 4
gpt4 key购买 nike

我正在尝试为每个 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>

最佳答案

与其遍历每个 data.carImage,不如考虑先计算所需的 div 数量:

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
}

关于javascript - 每个 div 添加 2 个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com