我如何计算孩子的数量? [英] How can I count the number of children?

查看:75
本文介绍了我如何计算孩子的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

<ul>
  <li>
  <li>
  <li>
  ...
</ul>

我需要jQuery来计算列表中的项目数.

I need jQuery to count the number of items in my list.

推荐答案

您可以使用 .length ,像这样:

You can use .length, like this:

var count = $("ul li").length;

.length 告诉您找到了选择器多少个匹配项,因此它计算了多少个<li><ul>元素下...如果有子子级,请使用"ul > li"代替,仅获取 direct 子级.如果页面中还有其他<ul>元素,只需更改选择器以使其仅与他的选择器匹配,例如,如果选择器具有ID,则您将使用"#myListID > li".

.length tells how many matches the selector found, so this counts how many <li> under <ul> elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other <ul> elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li".

在其他不知道子类型的情况下,可以使用*(通配符)选择器或.children(),如下所示:

In other situations where you don't know the child type, you can use the * (wildcard) selector, or .children(), like this:

var count = $(".parentSelector > *").length;

或:

var count = $(".parentSelector").children().length;

这篇关于我如何计算孩子的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆