如何使用jQuery向第一个孩子添加课程? [英] How to add class to first child with jQuery?

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

问题描述

如何在具有特定索引的容器上添加一个元素类?

How do I add a class an element on a container with a certain index?

我现在正在尝试这会影响第一个元素(不会无论如何都要工作)

I'm trying this right now which should affect the first element (doesn't work anyway)

$('#resultsBox li:first-child').addClass('aaaa');

但我希望能够更改其索引容器中任何元素的类。

But I want to be able to change class of any element in it's container having the index.

EG如果我想修改index = 2的元素。

EG if I want to modify element with index = 2.

<div id="resultsBox">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>

应该成为:

<div id="resultsBox">
<ul>
<li></li> // Index 0
<li></li> // Index 1
<li class="selected"></li> // Index 2
</ul>
</div>


推荐答案

使用 :第一个 选择器:

Use :first selector:

$('#resultsBox li:first').addClass('aaaa');

对于第三个元素选择,您可以使用 每个() 方法:
这是jsFiddle。

and for the third element selection, you can use each() method: Here is jsFiddle.

$('ul li').each(function(i) {
    if ( i === 2 ) {
       $(this).addClass('aaaa');
    }
});

或者您可以使用 eq 像Jamiec& amp; MrThys提到:但是当事情变得复杂时,每种方法都会非常有用。

or you can do this with eq method like Jamiec & MrThys mentioned: but each method will be much usefull when things getting complicated.

$('#resultsBox li').eq(2).addClass('aaaa');

这篇关于如何使用jQuery向第一个孩子添加课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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