Javascript 如何选择类名“nav”的 <ul> 中的所有 <li>?

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

How to select all <li> in an <ul> with a classname "nav"?

javascriptjquerycssjquery-selectors

提问by Alexander

Having a real hard time with this since I'm new to jQuery, but I'm not sure whether the tutorial I'm working on is broken or if it's me but I'm using the following code to select all li in an ul with a class of nav.

因为我是 jQuery 的新手,所以这真的很难,但我不确定我正在处理的教程是坏的还是我的,但我正在使用以下代码选择 ul 中的所有 li与一类导航。

$(".nav ul li");

Is this correct? Could someone point me in the right direction?

这样对吗?有人能指出我正确的方向吗?

回答by Alexander

Constructively,

建设性地,

  1. All ulelements:

    $("ul")
    
  2. All ulelements with a classname nav:

    $("ul.nav")
    
  3. All lielements under all ulelements with a classname nav:

    $("ul.nav li")
    
  1. 所有ul元素:

    $("ul")
    
  2. ul具有类名的所有元素nav

    $("ul.nav")
    
  3. 具有 classname 的所有li元素下的所有ul元素nav

    $("ul.nav li")
    

回答by Bryan Myers

Here's a tip that will help people learn selectors:

这里有一个技巧可以帮助人们学习选择器:

Use the Chrome browser Open up any page Right click on the page and select "Inspect element" In the element inspector select the Console tab

使用 Chrome 浏览器 打开任何页面 右键单击​​页面并选择“检查元素” 在元素检查器中选择控制台选项卡

You can type commands right into this console. Try a few selectors only and see what you get. If you type $('p') and hit enter it will list out all the p elements. If you enter $('ul.nav li) it will show you if that selector works (returns anything). If the command does not result in a valid selector it will return [].

您可以直接在此控制台中键入命令。只尝试几个选择器,看看你会得到什么。如果您输入 $('p') 并按回车键,它将列出所有 p 元素。如果您输入 $('ul.nav li) 它将显示该选择器是否有效(返回任何内容)。如果命令没有产生有效的选择器,它将返回 []。

回答by nbrooks

Append it after the element selector:

将其附加在元素选择器之后

$("ul.nav li");

This selects all <li>elements in a <ul class="nav">element

此选择所有<li>的元件<ul class="nav">元件

See the docs: http://api.jquery.com/class-selector/

请参阅文档:http: //api.jquery.com/class-selector/

回答by adeneo

select all li in an ul with a class of nav

选择具有一类导航的 ul 中的所有 li

like so, selects all li's in an ul with the .navclass:

像这样,选择 ul 中的所有 li.nav类:

$('ul.nav li')

回答by hyankov

All li in an ul with a class of nav:

ul 中的所有 li 具有一类导航:

$("ul.nav li");

回答by murphy1312

$('ul.nav li')

As suggested selects ALL the <li />in <ul class="nav" />. If you only want the immediate children use:

按照建议选择 ALL <li />in <ul class="nav" />。如果你只想要直接的孩子使用:

$('ul.nav > li')

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator