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

Ric*_*wis 19 javascript ajax jquery slick.js

I am using Slick for a carousel implementation and everything works fine when the pages loads.What I am trying to achieve is that when i make an Ajax call to retrieve new data I still want the slick carousel implementation, at the moment i lose it.

I have put the call for slick into a function

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

and then I call the function within my success callback

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

But the function isn't being called. How can I reinitialize this js?

小智 17

你应该使用unslick方法:

function getSliderSettings(){
  return {
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  }
}

$.ajax({
  type: 'get',
  url: '/public/index',
  dataType: 'script',
  data: data_send,
  success: function() {
    $('.skills_section').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
    $('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
    $('.skills_section').slick(getSliderSettings()); /* Initialize the slick again */
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,我不得不使用`$('.slick-media').slick('unslick').slick('reinit');` (2认同)

小智 14

最好的方法是在重新初始化之后销毁光滑的滑块.

function slickCarousel() {
  $('.skills_section').slick({
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  });
}
function destroyCarousel() {
  if ($('.skills_section').hasClass('slick-initialized')) {
    $('.skills_section').slick('destroy');
  }      
}

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


jda*_*net 13

这应该工作.

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
    success: function() {
        $('.skills_section').slick('reinit');
      }
});
Run Code Online (Sandbox Code Playgroud)

  • 根据他们的文档,这只是一个事件.但我只是在我的一个旋转木马上尝试这种方法,它确实似乎有效. (4认同)

Mih*_*att 11

$('#slick-slider').slick('refresh'); //Working for slick 1.8.1
Run Code Online (Sandbox Code Playgroud)


web*_*mad 4

注意:我不确定这是否正确,但您可以尝试一下,看看是否有效。

有一种unslick方法可以取消初始化轮播,因此您可以在重新初始化它之前尝试使用该方法。

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
    success: function() {
        $('.skills_section').unslick();  // destroy the previous instance
        slickCarousel();
      }
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。