概述 .size()
返回值:Number
描述:返回的jQuery对象匹配的DOM元素的数量。
.size()
方法从jQuery 1.8开始被废弃。使用.length
属性代替。
.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="http://code.jquery.com/jquery-latest.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>