首页 > 解决方案 > jQuery计数器并添加一个类但不是前两个?

问题描述

我正在检查我拥有的列表项目,如果有两个以上,那么我添加一个类。这工作正常,但我希望类在前两个列表项之后开始添加。我不确定如何做不包括将类添加到前两个的部分。这是我的代码:

$(document).ready(function() {
  //Checking how many time the class appears
  var numItems = $('ul.singleMagazine li').length;
  if (numItems > 2) {
    alert(numItems);
    //Want to add this class but not to the first two - exclude first two list items and then add it to the rest. How to do it?
    $('ul.singleMagazine li').addClass("newClass");
  }
});

我将如何做排除部分?

标签: javascriptjquery

解决方案


li元素应该是兄弟元素,因此您可以使用选择gt()器:

$('ul.singleMagazine li:gt(1)').addClass("newClass");

另请注意,length检查是多余的,好像上面的项目少于两个无论如何都不会做任何事情。


推荐阅读