javascript - 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");
}
});
我将如何做排除部分?
解决方案
li
元素应该是兄弟元素,因此您可以使用选择gt()
器:
$('ul.singleMagazine li:gt(1)').addClass("newClass");
另请注意,length
检查是多余的,好像上面的项目少于两个无论如何都不会做任何事情。
推荐阅读
- php - 使用相同的 id Laravel 再次存储数据
- pandas - 将日期操作代码转换为函数,然后将其应用于多列
- reactjs - 在“加载”时反应可加载(延迟加载)?
- c# - 使用 OLEDB 提供程序连接到 Access 数据库崩溃(自 Office 365 Build 12430.20184 起)
- python - keep_prob: 0.8 是什么意思?
- curl - 通过 curl 向 API 发送音频数据
- python - 如果答案是随机的,我如何追踪对原始答案的响应?
- google-cloud-platform - 在 GKE 中使用 N2 机器类型 - (Google Kubernetes Engine)
- c - 我尝试在 C 中为链表编写代码
- python - Pandas 数据框计算过去 3 年同月的平均值并附加在同一数据框中