使用jQuery的第n个类? [英] nth-of-class using jQuery?

查看:81
本文介绍了使用jQuery的第n个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

<div id="wrapper">
  <div class="class_1"></div>
  <div class="class_1"></div>
  <div class="class_2"></div>
  <div class="class_2"></div>
  <div class="class_2"></div>
  <div class="class_2"></div>
</div>

是否可以使用jQuery选择每秒 .class_2?

Is it possible to select every second .class_2 using jQuery?

我不想在#wrapper

我尝试过的事情:

:nth-child-这正在计算所有div

:nth-child - this is counting all divs

:nth-of-type-这也在计算所有div

:nth-of-type - this is also counting all divs

例如,我只想每隔div用.class_2选择一个div并添加一些类.

I want to select for example every second div only with .class_2 and add some class.

推荐答案

问题:

例如,我只想使用.class_2每隔一个div选择一次"

"I want to select for example every second div only with .class_2"

解决方案:

我相信您可以在此使用 :odd 实例,例如:

Solution:

I believe you could use :odd in this instance, e.g:

$('#wrapper > div.class_2:odd')

尽管将:odd filter() 串联更快的方法:

Although concatenating :odd with filter() would actually be the faster way:

$('#wrapper > div.class_2').filter(':odd')

这会用class_2选择每个div,并根据它们是奇数还是偶数对它们进行过滤.

This selects every div with class_2, and filters them based on whether or not they are odd or even.

jsFiddle在这里.

jsFiddle here.

基于0的索引 实际上意味着具有讽刺意味的是, :odd选择第二,第四,第六个元素,等等.

0-based indexing actually means that ironically, :odd selects the second, fourth, sixth element etc.

这篇关于使用jQuery的第n个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆