如何使用 jquery 为第一个列表项应用活动类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4077339/
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
How to apply active class for first list item using jquery
提问by Aadi
<div class="accordion">
<ul class="navigation">
<li>Lorem</li>
<li>Ipsum</li>
<li>Donor</li>
</ul>
<ul class="navigation">
<li>Test</li>
<li>Demo</li>
<li>Donor</li>
</ul>
</div>
How can we apply a class which is 'active' to first 'li' (ie;Lorem) only, not for all first 'li' under 'ul' using jquery. I would like to get output as
我们如何才能将“活动”的类应用到第一个“li”(即 Lorem),而不是使用 jquery 将“ul”下的所有第一个“li”应用到。我想得到输出
<div class="accordion">
<ul class="navigation">
<li class="active">Lorem</li>
<li>Ipsum</li>
<li>Donor</li>
</ul>
<ul class="navigation">
<li>Test</li>
<li>Demo</li>
<li>Donor</li>
</ul>
</div>
回答by Nick Craver
You can use :first
(as opposed to :first-child
which would get the first per-<ul>
), and .addClass()
like this:
您可以使用:first
(而不是使用:first-child
第一个 per- <ul>
),.addClass()
如下所示:
$(".accordion li:first").addClass("active");
Or .first()
, which is an alias for .eq(0)
or .slice(0,1)
even, like this:
或者.first()
,它是.eq(0)
or .slice(0,1)
even的别名,像这样:
$(".accordion li").first().addClass("active");
//or
$(".accordion li").eq(0).addClass("active");
//or
$(".accordion li:eq(0)").addClass("active");
//or
$(".accordion li").slice(0,1).addClass("active");
There are a few ways to go about it...though I prefer :first
or .first()
for clarity.