简体   繁体   English

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

[英]How to select all <li> in an <ul> with a classname “nav”?

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? 有人能指出我正确的方向吗?

Constructively, 建设性的,

  1. All ul elements: 所有ul元素:

     $("ul") 
  2. All ul elements with a classname nav : 带有classname nav所有ul元素:

     $("ul.nav") 
  3. All li elements under all ul elements with a classname nav : 所有li下的所有元素ul与类名的元素nav

     $("ul.nav li") 

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. 如果您输入$('p')并按Enter键,它将列出所有p元素。 If you enter $('ul.nav li) it will show you if that selector works (returns anything). 如果输入$('ul.nav li),它将显示该选择器是否有效(返回任何内容)。 If the command does not result in a valid selector it will return []. 如果该命令没有产生有效的选择器,它将返回[]。

Append it after the element selector : 元素选择器后面添加它:

$("ul.nav li");

This selects all <li> elements in a <ul class="nav"> element 这将选择<ul class="nav">元素中的所有<li>元素

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

select all li in an ul with a class of nav 使用导航类选择ul中的所有li

like so, selects all li's in an ul with the .nav class: 像这样,用.nav类选择ul中的所有li:

$('ul.nav li')

所有带有导航类的ul中的li:

$("ul.nav li");
$('ul.nav li')

As suggested selects ALL the <li /> in <ul class="nav" /> . 建议选择<ul class="nav" />所有<li /> <ul class="nav" /> If you only want the immediate children use: 如果您只想让直系孩子使用:

$('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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM