.size()

.size() 官网原E文: Number

描述: 返回的jQuery对象匹配的DOM元素的数量。

  • version added: 1.0.size()

假设页面上有下面一个简单的无序列表:

<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

我们通过调用 .size() 来获取列表项的数目:

alert('Size: ' + $('li').size());

于是就显示了列表项的个数:

Size: 2

你也可以使用 .length 属性来代替,他会略微快那么一点点。

Example:

统计divs。 点击添加更多。

<!DOCTYPE html>
<html>
<head>
  <style>body { cursor:pointer; }
 div { width:50px; height:30px; margin:5px; float:left; background:blue; }
 span { color:red; }
 </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <span></span>

 <div></div>
<script>$(document.body).click(function () { $(document.body).append($("<div>"));
var n = $("div").size();
$("span").text("There are " + n + " divs." + "Click to add more.");}).click(); // trigger the click to start</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订