jQuery:计算列表元素的数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/605969/
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
jQuery: Count number of list elements?
提问by Tom
I've got a list that is generated from some server side code, before adding extra stuff to it with jQuery I need to figure out how many items are already in it.
我有一个从一些服务器端代码生成的列表,在使用 jQuery 添加额外的东西之前,我需要弄清楚其中已经有多少项。
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
</ul>
回答by cletus
Try:
尝试:
$("#mylist li").length
Just curious: why do you need to know the size? Can't you just use:
只是好奇:为什么你需要知道尺寸?你不能只使用:
$("#mylist").append("<li>New list item</li>");
?
?
回答by Nick Allen
var listItems = $("#myList").children();
var count = listItems.length;
Of course you can condense this with
当然,您可以将其浓缩为
var count = $("#myList").children().length;
For more help with jQuery, http://docs.jquery.com/Main_Pageis a good place to start.
有关 jQuery 的更多帮助,请从http://docs.jquery.com/Main_Page开始。
回答by Alex Nguyen
You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call. So the best way:
调用 .size() 方法或 .length 属性时,您会得到相同的结果,但首选 .length 属性,因为它没有函数调用的开销。所以最好的方法是:
$("#mylist li").length
回答by ROARSTAR
and of course the following:
当然还有以下内容:
var count = $("#myList").children().length;
can be condensed down to: (by removing the 'var' which is not necessary to set a variable)
可以浓缩为:(通过删除不需要设置变量的“var”)
count = $("#myList").children().length;
however this is cleaner:
但是这更干净:
count = $("#mylist li").size();
回答by Andrew Barrett
I think this should do it:
我认为应该这样做:
var ct = $('#mylist').children().size();
回答by Nui_CpE
try
尝试
$("#mylist").children().length
回答by M.Ganji
Count number of list elements
计算列表元素的数量
alert($("#mylist > li").length);
回答by Penny Liu
Another approach to count number of list elements:
计算列表元素数量的另一种方法:
var num = $("#mylist").find("li").length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
</ul>
回答by Bashirpour
$("button").click(function(){
alert($("li").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Count the number of specific elements</title>
</head>
<body>
<ul>
<li>List - 1</li>
<li>List - 2</li>
<li>List - 3</li>
</ul>
<button>Display the number of li elements</button>
</body>
</html>