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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:51:47  来源:igfitidea点击:

How to select a li with a specific class?

jqueryjquery-selectorsdom-traversal

提问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 lithat 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 ulid has been specified:

一旦ul指定了id,您就可以使用该类:

$("#attached_deals_tab .active");

Unless you have something other than lis in there and that something is also being applied the activeclass, which would be strange.

除非你有除lis以外的其他东西,并且有些东西也被应用到这个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 ulcan only have lielements as its children, so when using the child selector, .activeshould 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').(...)