如何从 jquery 中只有一个类的 ul 中选择 li

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9112301/
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-27 10:20:39  来源:igfitidea点击:

How to select li from ul having only one class in jquery

jquery

提问by Abhishek

I want to select all li elements from ul having class "one" only

我想从 ul 中选择所有 li 元素,只有“一”类

<ul class="one">
<li class="heading">
<li class="list">
<li class="list">
<li class="list">
<li class="list">
</ul>       
<ul class="one two ">
<li class="heading">
<li class="list">
<li class="list">
<li class="list">
<li class="list">
</ul>                        

回答by Andy E

Easiest:

最简单:

$('ul[class="one"] li');

Alternative, select .onebut not .two:

替代,选择.one但不.two

$('ul.one:not(.two) li');

回答by Brian Scott

You can use the jquery filter function to get a count of how many classes have been assigned to the element. When looking for all UL's with class 'one' only then the number of unique classes against the item will be 1. Once you have the filtered UL's you can simply select the sub LI's.

您可以使用 jquery 过滤器函数来计算已分配给元素的类数。当查找所有类别为“1”的 UL 时,针对该项目的唯一类别的数量将为 1。一旦您筛选出 UL,您就可以简单地选择子 LI。

var listItems = 
$('ul.one')
.filter(function(index) {
  return $(this).attr('class').split(' ').length == 1;
})
.find('li');