我目前正在单个页面上从每篇文章中收集div,然后对其进行遍历以查找包含类.so-widget-hello-world-widget
的所有div。一切正常,但是我很难将其限制为每篇文章仅5
。
我尝试使用slice
,limit
并添加一个计数器,但似乎无济于事。
这里有明显的东西我想念吗?
jQuery(function($) {
$('article').each(function(index, obj){
var product = $(this).find('.so-widget-hello-world-widget')
$(this).append(product)
});
});
答案 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>