为什么wrapAll在无限滚动中有很多div?

时间:2017-08-15 06:49:18

标签: javascript jquery html css

最后一个问题是: Wrap some divs with Two different columns

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/infinite-scroll@3/dist/infinite-scroll.pkgd.min.js"></script>

    <script type="text/javascript">
    $('.wrapper').each(function() {
      $(this).find(".lpost").wrapAll('<div class="left_columns"></div>')
      $(this).find(".rpost").wrapAll('<div class="right_columns"></div>')
    })
    </script>

    <div class="wrapper">
      <div class="rpost">-115</div>
      <div class="lpost">-91</div>
      <div class="lpost">-99</div>
      <div class="rpost">-181</div>
      <div class="lpost">-19</div>
      <div class="rpost">-135</div>
      <div class="rpost">-85</div>
      <div class="lpost">-39</div>
    </div>

        <script type="text/javascript">
        var $container = $('.wrapper').infiniteScroll({
            path: '.next-post',
            append: '.post',
            hideNav: '.pagination',
            status: '.page-load-status',
        });
        $container.on('append.infiniteScroll',
        function(event, response, path, items) {
            $(function() {
                $('.wrapper').each(function() {
                  $(this).find(".lpost").wrapAll('<div class="left_columns"></div>')
                  $(this).find(".rpost").wrapAll('<div class="right_columns"></div>')
                })
            });
        });
        </script>

如果向下滚动三页结果:

<div class="wrapper">
  <div class="left_columns">
    <div class="left_columns">
      <div class="left_columns">
          <div class="lpost">-91</div>
          <div class="lpost">-99</div>
          <div class="lpost">-19</div>
          <div class="lpost">-39</div>
      </div>
    </div>
  </div>
</div>

有太多的left_columns和right_columns div 如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您应该检查.right_columns.left_columns是否存在:

$('.wrapper').each(function() {
    var lpost = $(this).find(".lpost"),
        rpost = $(this).find(".rpost"),
        lcol  = $(this).find('.left_columns');

    if(lcol.length){ 
        var rcol = $(this).find('.right_columns');
        lpost.appendTo(lcol);
        rpost.appendTo(rcol);
    }else{
        lpost.wrapAll('<div class="left_columns"></div>');
        rpost.wrapAll('<div class="right_columns"></div>');
    }
})