使用 jQuery 获取 UL 的第一个 LI 的 ID

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

Get ID of first LI of UL with jQuery

jquerycss-selectors

提问by st4ck0v3rfl0w

<ul id="someList">
<li id="listItem1">List 1</li>
<li id="listItem2">List 2</li>
</ul>

Maybe I need to brush up on my selectors, but how would you grab the first ID of ul#someList?

也许我需要复习一下我的选择器,但是你将如何获取 ul#someList 的第一个 ID?

Also if I'm prepending LI's to ul#someList, will I need to grab the first LI's ID in a different way?

另外,如果我在 ul#someList 前面加上 LI,我是否需要以不同的方式获取第一个 LI 的 ID?

回答by user11977

$('ul#someList li:first')is what you're looking for.

$('ul#someList li:first')就是你要找的。

回答by Corey Sunwold

Your best bet is to use the first selector.

最好的办法是使用第一个选择器。

var id = $("ul#someList li:first").attr("id");

or

或者

var id = $("ul#someList li:first").get(0).id;

回答by SoftwareGeek

Try, ****.slice( start, [ end ] )****`

试试吧,****.slice(开始,[结束])****`

<ul>
  <li id='l1'>list item 1</li>
  <li id='l2'>list item 2</li>
  <li id='l3'>list item 3</li>
  <li id='l4'>list item 4</li>
  <li id='l5'>list item 5</li>
</ul>

$('li').slice(2).attr('id');

回答by Selim Reza

This may be another solution:

这可能是另一种解决方案:

$('#someList li:nth-child(1)').attr("id");