jQuery 如何计算孩子的数量?

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

How can I count the number of children?

jquery

提问by aneuryzm

I have a list

我有一个清单

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

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

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

回答by Nick Craver

You can use .length, like this:

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

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

.lengthtells 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 directchildren. 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".

.length告诉选择器找到多少匹配项,因此这会计算您拥有的<li><ul>元素的数量……如果有子子项,请改用"ul > li"仅获取直接子项。如果您<ul>的页面中有其他元素,只需更改选择器以仅匹配他的元素,例如,如果它具有您要使用的 ID "#myListID > li"

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

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

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

or:

或者:

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

回答by Zach Saucier

You don't need jQuery for this. You can use JavaScript's .childNodes.length.

为此,您不需要 jQuery。您可以使用 JavaScript 的.childNodes.length.

Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

如果您不想包含默认文本节点(默认为空),请确保减去 1。因此,您将使用以下内容:

var count = elem.childNodes.length - 1;

回答by Zach Saucier

Try to get using:

尝试使用:

var count = $("ul > li").size();
alert(count);

回答by Oguzhan

What if you are using this to determine the current selector to find its children so this holds: <ol>then there is <li>s under how to write a selector var count = $(this+"> li").length;wont work..

如果您使用它来确定当前选择器以找到它的子代怎么办,所以这成立:<ol>那么<li>如何编写选择器将 var count = $(this+"> li").length;不起作用..

回答by Youssof H.

You can do this using jQuery:

您可以使用 jQuery 执行此操作:

This method gets a list of its children then counts the length of that list, as simple as that.

此方法获取其子项的列表,然后计算该列表的长度,就这么简单。

$("ul").find("*").length;

The find() method traverses DOM downwards along descendants, all the way down to the last descendant.

find() 方法沿着后代向下遍历 DOM,一直向下遍历到最后一个后代。

Note:children() method traverses a single level down the DOM tree.

注意:children() 方法向下遍历 DOM 树的单个级别。