如何知道父母的孩子数?

Vin*_*rez 2 javascript jquery jquery-selectors

在特定项目上,我如何知道当前的子计数是多少?

例如:

<div id="parent">
  <img id="lorem" />
  <img id="ipsum" />
  <img id="dolor" />
  <img id="sit" />
  <img id="amet" />
</div>
Run Code Online (Sandbox Code Playgroud)

我怎么知道$('#sit')是其兄弟姐妹中的第4名?我可以迭代所有的孩子并计算,但这个接缝很慢,特别是因为我需要经常更新它,因为有数百个兄弟姐妹,我只需要针对最后5个兄弟姐妹

我的解决方案的解决方法是能够独立定位最后5个孩子.知道怎么样?

PSL*_*PSL 5

您可以使用 .index()

$('#sit').index() // will give you the index (zero based) with respective to its siblings.
Run Code Online (Sandbox Code Playgroud)

如果你想找到父母的最后5个孩子,试试:

 $('#parent').children(':nth-last-child(-n + 5)');
Run Code Online (Sandbox Code Playgroud)