限制从.find()返回的div数量

时间:2018-12-07 05:09:20

标签: javascript jquery

我目前正在单个页面上从每篇文章中收集div,然后对其进行遍历以查找包含类.so-widget-hello-world-widget的所有div。一切正常,但是我很难将其限制为每篇文章仅5

我尝试使用slicelimit并添加一个计数器,但似乎无济于事。

这里有明显的东西我想念吗?

jQuery(function($) {
    $('article').each(function(index, obj){
        var product = $(this).find('.so-widget-hello-world-widget')
        $(this).append(product)
    });
});

1 个答案:

答案 0 :(得分:5)

使用lt选择器documetation

$(this).find('.so-widget-hello-world-widget:lt(5)')

$('article').each(function(index, obj) {
  var products = $(this).find('.so-widget-hello-world-widget:lt(5)');
  products.each(function(index, el) {
    $(el).css({
      background: 'red'
    });
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
  <div class='so-widget-hello-world-widget'>div1</div>
  <div class='so-widget-hello-world-widget'>div2</div>
  <div class='so-widget-hello-world-widget'>div3</div>
  <div class='so-widget-hello-world-widget'>div4</div>
  <div class='so-widget-hello-world-widget'>div5</div>
  <div class='so-widget-hello-world-widget'>div6</div>
  <div class='so-widget-hello-world-widget'>div7</div>
  <div class='so-widget-hello-world-widget'>div8</div>
  <div class='so-widget-hello-world-widget'>div9</div>
  <div class='so-widget-hello-world-widget'>div10</div>
</article>