首页 > 解决方案 > 动态初始化 swiper 滑块无法解释的行为

问题描述

我必须动态创建 swiper 的实例。这些 swiper 具有动态填充的图像内容。我一整天都在与我缺乏技能的情况作斗争,无法让它发挥作用。

没有 javascript 控制台错误,所以我假设某些东西根本上是错误的,但我不知道它是什么。

这是代码:

<!-- The sliders are initiated very standard way, i skipped showing them. These are my paginations where I cannot get the pagination to be rendered -->

<div class="secondary-0 swiper-pagination-clickable swiper-pagination-bullets"></div>
<div class="secondary-1 swiper-pagination-clickable swiper-pagination-bullets"></div>
<div class="secondary-2 swiper-pagination-clickable swiper-pagination-bullets"></div>

<script>
    // I get lots of image data from php here
    var imagearrays = <?php echo json_encode( $images_multiarray_js ); ?>;

    // initialize variables for use in the loop. 
    var i;
    var subNameArray = [];
    var subSwiper = [];

    // Loop through the imagearrays variable and initiate swipers.
    for (i = 0; i < imagearrays.length; i++) {
        subNameArray[i] = imagearrays[i].imagenames;
        subSwiper = new Swiper('.subswiper-' + i, { // all my swiper-containers have extra class "subswiper-0" "subswiper-1" etc.
            pagination: { // my main issue: I cannot get this pagination to render. WHY?
                el: '.secondary-' + i, //my paginations have class like "secondary-0"
                clickable: true,
                renderBullet: function (index, className) {
                    return '<span class="' + className + '"><div class="pagination-ball"></div>' + subNameArray[index] + '</span>';
                }
            },
            loop:true,
            effect: 'fade',
            clickable:true,
            disableOnInteraction:false,
        });
    }
</script>

这就是我的 imagearrays 变量的样子,只是为了向您展示它很好。

[
  {"controllertype":false,"imagenames":["name1","name2"]},
  {"controllertype":true,"imagenames":["name3","name4"]},
  {"controllertype":false,"imagenames":["name5","name6"]}
]

我试图在调试 JS 模式下逐行进行,但看起来控制台只是跳过了“new Swiper(...”行以及其中的所有内容。同样,控制台中没有错误。

标签: javascriptdynamicswiper

解决方案


如何感觉自己很愚蠢:

  1. 花半天时间弄清楚为什么你的代码不起作用
  2. 一时兴起检查您的 swiper 选择器类是否附加到正确的 html 元素并意识到它不是
  3. 在stackoverflow中哭泣

对不起各位,这个问题没用。该 d'oh 修复程序一切正常。


推荐阅读