Javascript 如何使用jQuery将类添加到第一个孩子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11859509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:25:50  来源:igfitidea点击:

How to add class to first child with jQuery?

javascriptjquery

提问by lisovaccaro

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 if I want to modify element with index = 2.

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

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

Should become:

应该变成:

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

回答by Barlas Apaydin

Use :firstselector:

使用:first选择器:

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

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

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

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

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

或者你可以用eq方法来做到这一点,比如 Jamiec & MrThys 提到的:但是当事情变得复杂时,每种方法都会非常有用。

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

回答by Thizzer

The cleanest way of achieving this would be:

实现这一目标的最干净的方法是:

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

Documentation on the .eq method can be found here: http://api.jquery.com/eq/

关于 .eq 方法的文档可以在这里找到:http://api.jquery.com/eq/

回答by Gareth Parker

Use the :first selector, or the :nth-child selector. I mention the :nth-child selector simply in case you want to add classes to anything other than the first. You can also use :nth-child in plain CSS without javascript if you want

使用 :first 选择器或 :nth-child 选择器。我提到 :nth-child 选择器只是为了以防万一您想将类添加到除第一个之外的任何内容。如果需要,您也可以在没有 javascript 的纯 CSS 中使用 :nth-child

$("#resultBox li:nth-child(1)").addClass('aaa');

回答by ztvmark

For select ul

对于选择 ul

$("#resultsBox ul").first().addClass( "aaaa" );

For select first li

对于选择第一个 li

$("#resultsBox ul li").first().addClass( "aaaa" );

回答by Jamiec

eq selector

eq selector

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

or eq function

或者 eq function

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