.size()
分类:建议弃用 > 建议弃用于1.8 | 杂项 > DOM元素的方法
描述:返回jQuery对象中的元素的数量。
加入于: 1.0
.size()该方法不接受任何参数
在jQuery 1.8中,.size()方法被建议弃用了。请用.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 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>
演示结果