简体   繁体   中英

Previous divs with jQuery does not work after Ajax call

I have two scripts:

  1. The first one is image carousel. It uses jQuery slick slider.
  2. The second one is an Ajax script that loads contents as page scrolls down.

Here is my code:

function slider () {
  var $arrows = $('.arrows');
  var $next = $arrows.children(".slick-next");    
  var $prev = $arrows.children(".slick-prev");

  var slick = $('.your-class').slick({
    appendArrows: $arrows
  });

  $('.slick-next').on('click', function (e) {
    var i = $next.index( this )
    slick.eq(i).slickNext();
  });

  $('.slick-prev').on('click', function (e) {
    var i = $prev.index( this )
    slick.eq(i).slickPrev();
  });
}

$(document).ajaxComplete(slider);

Below is the scroll content load with Ajax:

$(document).ready(function(){

  function slider () {

    var $arrows = $('.arrows');
    var $next = $arrows.children(".slick-next");    
    var $prev = $arrows.children(".slick-prev");

    var slick = $('.your-class').slick({
      appendArrows: $arrows
    });

    $('.slick-next').on('click', function (e) {
      var i = $next.index( this )
      slick.eq(i).slickNext();
    });

    $('.slick-prev').on('click', function (e) {
      var i = $prev.index( this )
      slick.eq(i).slickPrev();
    });
  }

  $(document).ajaxComplete(slider);

  var flag = 0;

  $.ajax({
    type: "GET",
    url: "getdata.php",
    data: {
      'offset': 0,
      'limit': 10
    },

    success: function(data){
      $('.rowmasonry').append(data);
      flag += 10;
    },

  });

  $(window).scroll(function(){
    if($(window).scrollTop() >= $(document).height() - $(window).height()-500){
      $.ajax({
        type: "GET",
        url: "getdata.php",
        data: {
          'offset': flag,
          'limit': 10
        },

        success: function(data){
          $('.rowmasonry').append(data);
          flag += 10;
        },

      });
    }

  });

});

The problem is that the first 10 contents that are loaded work properly. However, as I scroll down, and another 10 contents come, the first 10 contents that were loaded do not respond.

How do I bind the image slider to Ajax, so that all contents on the page work with jQuery?

Thanks for your help.

You are just appending new elements to DOM. In order to update slick you need to reInit slick carousel or if you are sure about the slide markup then you can use slickAdd method provided by plugin.

$.ajax().done(function(data){ $('.your-class').slick('slickAdd', data); });

ref: http://kenwheeler.github.io/slick/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM