[英]Add Class to the first 5 elements within a div with jQuery
I swear I've done this before, but I'm trying to count the first 5 items within a div and then add a class to them and then add a class to the rest. 我发誓我之前已经做过,但是我试图计算div中的前5个项目,然后向其中添加一个类,然后向其余部分添加一个类。
I have this: 我有这个:
var counter = 0;
$('.images img').each(function(i) {
if (i == 0) {
counter = 0;
} else {
counter++;
}
if (counter < 5) {
$(this).addClass('this');
} else {
$(this).addClass('other');
}
});
which works, but I feel that it could be cleaned up a bit. 可以,但是我觉得可以清除一点。 Any suggestions to make this a bit leaner?
有什么建议可以使其更精简吗?
使用jQuery时,您可以使用:lt()
(索引从零开始)
$('.images img:lt(5)').addClass('this')
Easiest solution is to not use JavaScript, but just use a CSS Selector. 最简单的解决方案是不使用JavaScript,而仅使用CSS选择器。 nth child will let you target a range of items.
第n个孩子可以让您定位一系列商品。
li { background-color: yellow; } li:nth-child(-n+5) { background-color: green; }
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul>
If you want to use jQuery, you can simplify it with .slice(start, end)
如果要使用jQuery,则可以使用
.slice(start, end)
简化它。
var lis = $('li'); lis.slice(0,5).addClass('on'); lis.slice(5).addClass('off');
.off { background-color: yellow; } .on { background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul>
or you can use the function option in .addClass(function)
或者您可以在
.addClass(function)
使用function选项
$('li').addClass( function (index) { return index < 5 ? 'on' : 'off'; })
.off { background-color: yellow; } .on { background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul>
To achieve expected result , use below option 为了达到预期的效果,请使用以下选项
$('div').each(function(index) { if(index < 5){ $(this).addClass('mark') }else { return false; } })
.mark{ color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>1</div> <div>1</div>
Alternatively, you can go with pure css by using .images img:nth-child(-n+5) { stuff} 另外,您也可以使用.images img:nth-child(-n + 5){stuff}使用纯CSS
.test {
color: green;
background: yellow;
}
.img span:nth-child(-n+3) {
color: red !important;
background: blue;
}
<div class="img">
<span class="test">TEST</span>
<span class="test">TEST</span>
<span class="test">TEST</span>
<span class="test">TEST</span>
<span class="test">TEST</span>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.