当相同的 class 没有连续重复时,滚动到下一个 div 问题

Scroll to next div issue when the same class isn't continually repeated

当 div 之间有 HTML 时,在创建用于滚动到相同 class 的下一个元素的按钮时遇到一些问题。该按钮是一个“下一步 post”按钮,当 post 像这样设置时可以很好地工作。

<div class="new">Content</div>
<div class="new">Content</div>
<div class="new">Content</div>

当第一个 post 和其余 HTML 之间存在一些 HTML 时,它停止工作。

<div class="new">Content</div>
<div class="something-else">Content</div>
<div class="new">Content</div>
<div class="new">Content</div>

使用 jQuery 按钮创建成功,但当 post div 不连续在一起时按钮停止工作。

<div class="buttondiv">
<a id="down">Next post</a>
</div>

<script>
var $currentElement = $(".new").first();

$("#down").click(function () {
    var currentElement = $currentElement.next(".new");
    // Check if next element actually exists
    if(currentElement.length) {
        // If yes, update:
        // 1. $currentElement
        // 2. Scroll position
        $currentElement = currentElement;
    } else {
        $currentElement = currentElement = $(".new").first();
    }
    
    $('html, body').stop(true).animate({
        scrollTop: $(currentElement).offset().top- $('.sticky').height()
    }, 0);
    return false;
});

</script>

我已经尝试使用其他 jQuery 解决方案成功制作下一个 post 按钮,但当 post div 之间有东西时似乎也停止工作。

<script>
$(".buttondiv").click(function() {
  var $target = $('.new').next('.p');
  if ($target.length == 0)
    $target = $('.new');
    
  $('html, body').animate({
    scrollTop: $target.offset().top
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});

</script>

有任何解决此问题的建议吗?

next('.new') 更改为 nextAll('.new')

next() 仅 returns 下一个直系兄弟姐妹。在这种情况下,它检查 <div class="something-else">Content</div> 是否有 new class,但没有找到,所以 returns 什么都没有。

nextAll() 搜索所有以下兄弟姐妹。