Jquery将类添加到最后5个元素

时间:2022-03-11 14:28:36

i have lots of images:

我有很多图像:

<img src="images/img.jpg" alt="" />
<img src="images/img2.jpg" alt="" />
<img src="images/img3.jpg" alt="" />
<img src="images/img4.jpg" alt="" />
<img src="images/img5.jpg" alt="" />
<img src="images/img6.jpg" alt="" />
<img src="images/img7.jpg" alt="" />
<img src="images/img8.jpg" alt="" />

and so on...

等等...

How to add class only to last five images?

如何只将课程添加到最后五张图片?

Thanx

感谢名单

2 个解决方案

#1


12  

You can use slice() for that:

您可以使用slice():

$("img").slice(-5).addClass("myclass");

#2


1  

You can use jQuery filter jfiddle

您可以使用jQuery filter jfiddle

var lastimageIndex = $('img').length -1;
$('img').filter(function(index) {
    console.log(lastimageIndex - index - 6 < 0);
   return lastimageIndex - index - 5 < 0;
}).addClass("yourclass");​

#1


12  

You can use slice() for that:

您可以使用slice():

$("img").slice(-5).addClass("myclass");

#2


1  

You can use jQuery filter jfiddle

您可以使用jQuery filter jfiddle

var lastimageIndex = $('img').length -1;
$('img').filter(function(index) {
    console.log(lastimageIndex - index - 6 < 0);
   return lastimageIndex - index - 5 < 0;
}).addClass("yourclass");​