成功的Ajax调用后重新初始化Slick js

32

我正在使用Slick插件来实现轮播图功能,当页面加载时一切正常。但是我想要的是在通过Ajax调用检索新数据时仍然保留Slick轮播图效果,目前我失去了这个效果。

我将Slick调用放入了一个函数中。

function slickCarousel() {
  $('.skills_section').slick({
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  });
}

然后我在成功回调函数中调用该函数

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
      success: function() {
        slickCarousel();
      }
   });

但是这个函数并没有被调用。我该如何重新初始化这个js?


程序是否到达成功函数处理程序? - web-nomad
是的,它确实可以,那么我可能漏掉了什么吗? - Richlewis
由于走马灯已经初始化,您需要在重新初始化之前删除该事件处理程序。只是猜测。 - web-nomad
抱歉,这可能是一个愚蠢的问题,但您能提供一个例子吗? - Richlewis
请查看我的答案。 - web-nomad
13个回答

0

Slick 版本:1.8.0

 function getSliderSettings() {
                return {
                    slidesToShow: 3,
                    slidesToScroll: 1,
                    loop: true,
                    arrows: true,
                    dots: false,
                }
            }
    
    
    $.ajax({
            type: 'get',
            url: '/public/index',
            dataType: 'html',
            data: some_data,
            success: function(response) {
                    $('[data-role="slick-slider"]').slick('unslick');
                    $('[data-role="slick-slider"]').html($(response).html());
                    $('[data-role="slick-slider"]').slick(getSliderSettings());
              }
        });

0
虽然以上答案是正确的,但在更新数组后需要显示带有更新/新数据的新幻灯片,并且需要刷新slick滑块实例时,还有一个问题。
如果我们不这样做,那么不论数组是否已经更新,slick都会继续显示之前绑定的旧数据。
因此,使用现代框架和ES6方法的代码可能如下所示。
假设我们正在通过循环在vue、react、angular或alpine js等现代库中显示数据数组,并且我们有一个名为shops的数组要作为滑块显示。
每当有人触发某个操作时,数组(和最终的DOM)都会被更新,但我们必须手动告诉slick滑块根据新数组中的数据更新幻灯片数据。这里的数据以shops数组的形式存在。
  {
        shops: [],
        init() {
            let self = this;
            // watch for your data and provide callback function after it has been updated
            // this $watch is example from alpine js but similar could be available in other framrworks
            self.$watch('shops',(currentShops,oldShops) => {
                //currentshops holds the new value of shops after update
                //oldShops holds older value before update

                //first remove all slides that were attached with slick before shops array was updated (sorted for example)
                $('#shops-section-slider.slick-initialized').slick('slickRemove', null, null, true);
                //After this, add new slides after shops has been updated(sorted)
                // via template that accepts shop as an argument
                currentShops.forEach(function(shop,index) {
                    $('#shops-section-slider.slick-initialized').slick('slickAdd', self.getSliderTmpl(shop));
                })
                //after adding and removing is completed, 
                //finally just call refresh to prevent reinit entirely.
                $('#shops-section-slider.slick-initialized').slick('refresh');
            })
            //shopsPromise only does slider creation and other things when data has been updated in dom.
            shopsPromise.then(function(data) {
                //update shops here via data that has been recieved
                shops.push(data)
            }).then(function() {
                //crate slider after promise is resolved
                $('#shops-section-slider').not('.slick-initialized').slick({
                    //your slick settings
                })
            });
        },
        
        getSliderTmpl(shop) {
            return `<div class="col-12 col-md-6 col-lg-4 col-xl-4 d-flex flex-column shops-section">
                <div class="row flex-grow-1 flex-column flex-xxl-row">
                    <div class="col-12 col-xxl-6">
                        <div class="shops-img position-relative">
                            <strong class="shops-title-card d-block d-xxl-none">${shop.whateveravailable}</strong>
                        </div>
                    </div>
                    
                </div>
            </div>`;
        }
    }

在HTML中,我们甚至不需要<template>元素,它在alpine js中用作循环,因为它会创建错误的宽度和问题,由于有一个额外的幻灯片,所以我们可以省略它,从而仅通过js来管理整个幻灯片数据和模板。
<div class="row shops-section-wrapper" id="shops-section-slider"></div>

-1
在调用请求后,设置超时以初始化Slick Slider。
var options = {
    arrows: false,
    slidesToShow: 1,
    variableWidth: true,
    centerPadding: '10px'
}

$.ajax({
    type: "GET",
    url: review_url+"?page="+page,
    success: function(result){
        setTimeout(function () {
            $(".reviews-page-carousel").slick(options)
        }, 500);
    }
})

不要在开始时初始化Slick滑块。只有在AJAX超时后才进行初始化。这样应该适合你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接