jQuery 如何选择具有特定类的 li?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12604267/
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 select a li with a specific class?
提问by Houman
<ul id="attached_deals_tab" class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#Test1">Test1</a>
</li>
<li class="">
<a data-toggle="tab" href="#Test2">Test2</a>
</li>
</ul>
With a jquery like this, I could say get me all list items:
使用这样的 jquery,我可以说让我获取所有列表项:
$('#attached_deals_tab li');
But how can I say show me only the li
that has class="active"
? In one line please.
但是我怎么能说只给我看li
那个class="active"
呢?请在一行。
I know how to negate it:
我知道如何否定它:
$('#attached_deals_tab li:not(.active)');
But not the other way around...
但反过来不是...
回答by jholloman
$('#attached_deals_tab li.active');
回答by codebox
This should do it, the syntax is just the same as in CSS:
应该这样做,语法与 CSS 中的相同:
$('#attached_deals_tab li.active');
回答by Grant Thomas
You could just use the class once the ul
id has been specified:
一旦ul
指定了id,您就可以使用该类:
$("#attached_deals_tab .active");
Unless you have something other than li
s in there and that something is also being applied the active
class, which would be strange.
除非你有除li
s以外的其他东西,并且有些东西也被应用到这个active
类中,这会很奇怪。
回答by kapa
You should use the child selector to prepare your code for possible future nested lists:
您应该使用子选择器为将来可能的嵌套列表准备代码:
$('#attached_deals_tab > .active')
It will select only direct children. According to the specification, an ul
can only have li
elements as its children, so when using the child selector, .active
should suffice, no need to specify li.active
.
它将只选择直接子级。根据规范,anul
只能有li
元素作为它的子元素,所以当使用子选择器时,.active
应该就足够了,不需要指定li.active
.
By nested lists, I mean something like this:
通过嵌套列表,我的意思是这样的:
<ul id="attached_deals_tab">
<li class="active"></li>
<li></li>
<li>
<ul>
<li class="active"></li>
<li></li>
</ul>
</li>
</ul>
Reading the documentation on jQuery Selectorswill also help a lot.
阅读有关 jQuery 选择器的文档也会有很大帮助。
回答by SexyBeast
Simple, do
简单,做
$('#attached_deals_tab li.active').(...)