加载中...

size()


概述    .size()

返回值:Number

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

  • V : 1.0.size()

    • 这个方法不接受任何参数。

.size()方法从jQuery 1.8开始被废弃。使用.length属性代替。

.size()方法功能上等价于.length属性。但是.length 属性是首选的,因为它没有函数调用时的额外开销。

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

  1. <ul>
  2. <li>foo</li>
  3. <li>bar</li>
  4. </ul>

.size().length 识别的项目数:

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

结果两个提示:

Size: 2

Size: 2

示例

实例

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. body { cursor:pointer; min-height: 100px; }
  6. div { width:50px; height:30px; margin:5px;
  7. float:left; background:blue; }
  8. span { color:red; }
  9. </style>
  10. <script src="http://code.jquery.com/jquery-latest.js"></script>
  11. </head>
  12. <body>
  13. <span></span>
  14. <div></div>
  15. <script>
  16. $(document.body)
  17. .click(function() {
  18. $(this).append( $("<div>") );
  19. var n = $("div").size();
  20. $("span").text("There are " + n + " divs. Click to add more.");
  21. })
  22. // trigger the click to start
  23. .click();
  24. </script>
  25. </body>
  26. </html>

运行一下


还没有评论.