返回值:Numbersize()

返回 jQuery 对象中对应 DOM 元素的个数。

.size() 方法的功能和 .length 属性一样。但推荐使用 .length 属性,因为它没有函数调用时的额外开销。

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

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

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

alert( "Size: " + $("li").size() );
alert( "Size: " + $("li").length );

上述两个方法显示的列表项的个数如下:

Size: 2

Size: 2

示例:

统计 div 的个数。点击时添加一个 div。

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


<span></span>
 <div></div>


<script>


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


</script>
</body>
</html>

演示: