.size()

.size()返回类型:Integerversion deprecated: 1.8, removed: 3.0

描述:返回jQuery对象中元素的数目。

  • 增补版本:1.0.size()

    • 此方法不接受任何参数。

.size()方法在jQuery 1.8中被淘汰了。请用.length属性来代替。

.size()方法在功能上等同于.length属性;然而,.length属性是首选项,因为它没有调用函数的开销。

给定一个网页上的简单的无序列表:

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

.size().length两者都指示项数:

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

这产生了两个警告:

Size: 2

Size: 2

示例:

计数<div>。点击就添加更多<div>。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>size demo</title>
<style>
body {
cursor: pointer;
min-height: 100px;
}
div {
width: 50px;
height: 30px;
margin: 5px;
float: left;
background: blue;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>

演示: