首页 > 解决方案 > 在html中迭代数组

问题描述

我正在开发一个产品销售页面。我使用了一个 jquery 插件来实现轮播图像。

那是图书馆:

https://www.jqueryscript.net/demo/Carousel-Plugin-jQuery-RV-Gallery/

我正在使用静态图像进行测试,其中一些图像来自互联网。但我必须动态存储图像,所以我试图在 html 中迭代一个 ARRAY。该数组是 html 格式的。

对于arrayImagesProduct 的内容,我需要替换shopify 链接。每个产品,它可能有一个,两个,三个,......图像。所以我需要迭代数组。

我试过这个:

$("#productImages").html(arrayImagesProduct.join(''));

但随后滑块不起作用。我收到此错误:

Uncaught TypeError: Cannot read property 'clientWidth' of undefined
    at Gallery.countMoveRight (RV-gallery.js:121)
    at RV-gallery.js:36
    at dispatch (VM1025 jquery-1.12.4.js:5226)
    at elemData.handle (VM1025 jquery-1.12.4.js:4878)

function showProduct(productCode){
    var arrayImagesProduct = [];
    $.post('../ServletJson', {
        elem : 'productInfo',
        code: productCode,
    }, function(data) {
        $.each(data,function(t,elem){
            /* some stuff */


            arrayImagesProduct.push('<img class="gallery-item" src="../loadImgProduct.jsp?idImg='+elem.idImg+'&code=productCode">');

            
        });
            $("#productImages").html(arrayImagesProduct.join(''));
    });
}



如何在 html 中迭代 arrayImagesProduct 数组?

这里里面

<div class="gallery" id="productImages">

<!-- iterate arrayImagesProduct -->

<\div>
<body>
<div class="container-fluid">
    <div class="row image-gallery-container">
        <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 ">
            <div class="gallery" id="productImages">
                <img class="gallery-item" src="https://cdn.shopify.com/s/files/1/0122/2724/8185/products/0719_2019_Top1_b_ae870642-af0d-4655-811d-d597ed2a8bcc_720x.jpg?v=1574239406">
                <img class="gallery-item" src="https://cdn.shopify.com/s/files/1/0122/2724/8185/products/0719_2019_Top1_a_720x.jpg?v=1574239409">
           </div>
       </div>
   </div>
   <!-- more content -->
</div>

</body>
Uncaught TypeError: Cannot read property 'clientWidth' of undefined
    at Gallery.countMoveRight (RV-gallery.js:121)
    at RV-gallery.js:36
    at dispatch (VM1025 jquery-1.12.4.js:5226)
    at elemData.handle (VM1025 jquery-1.12.4.js:4878)

轮播正在实例化声明:

 <div class="gallery">
jQuery('.gallery').eq(0).initGallery({
    nav: ['<i class="material-icons">keyboard_arrow_left</i>', '<i class="material-icons">keyboard_arrow_right</i>'],
    close: "<i class='material-icons'>close</i>",
    aspectRatio: 3/2,
    showDots: true,
    showNavIfOneItem: false,
    showNav: false,
    arrows: true,
    transition: "slide",
    transitionTime: 700,
});


jQuery.fn.initGallery = function(options) {
      if(!options) {
          options={};
      }
      var galleries=[];
      for (let i=0; i<this.length; i++) {
          options.gallery = this.eq(i);
          galleries[i] = new Gallery(options);
      }
 };

标签: htmljqueryarraysloopsfor-loop

解决方案


推荐阅读