.each()
返回: jQuery
.each( function )
描述:迭代一个jQuery对象,针对每个匹配的元素执行一个函数。
该.each()方法被设计为简明地制作DOM循环构造,几乎不会出错。在调用它时,它会迭代遍作为jQuery对象的一部分的DOM元素。每次回调函数运行时,会传入当前的循环迭代数,它从0开始。更重要的是,回调函数是在当前DOM元素的上下文中引发的,所以关键词this引用了这个元素。
假设网页上有一个简单的无序列表:
<ul> <li>foo</li> <li>bar</li> </ul>
你可以选择这些列表项,并迭代它们:
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
为列表中的每个项目记录了消息:
0: foo 1: bar你可以从回调函数内部,通过返回false来停止循环。
注意:大多数返回jQuery对象的jQuery方法也会在jQuery集合中迭代元素的集合——这个过程即“隐式迭代”。
// 在这里,.each()方法是不必要的。
$( "li" ).each(function() {
$( this ).addClass( "foo" );
});
// 而是,你可以应用潜在的迭代。
$( "li" ).addClass( "bar" );
示例
迭代遍三个div,并设置它们的color属性。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
color: red;
text-align: center;
cursor: pointer;
font-weight: bolder;
width: 300px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>
<script>
$( document.body ).click(function() {
$( "div" ).each(function( i ) {
if ( this.style.color !== "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
</script>
</body>
</html>
演示结果
要想访问一个jQuery对象,而不是访问常规的DOM元素,请使用$(this)。举个例子:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
ul {
font-size: 18px;
margin: 0;
}
span {
color: blue;
text-decoration: underline;
cursor: pointer;
}
.example {
font-style: italic;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
<script>
$( "span" ).click(function() {
$( "li" ).each(function() {
$( this ).toggleClass( "example" );
});
});
</script>
</body>
</html>
演示结果
使用return false以提前跳出.each()循环。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 5px;
float: left;
border: 2px blue solid;
text-align: center;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>
<script>
$( "button" ).click(function() {
$( "div" ).each(function( index, element ) {
// element == this
$( element ).css( "backgroundColor", "yellow" );
if ( $( this ).is( "#stop" ) ) {
$( "span" ).text( "Stopped at div index #" + index );
return false;
}
});
});
</script>
</body>
</html>
演示结果