定义和用法
jQuery.each() 函数用于遍历指定的对象和数组。
语法
$.each( object, callback )
Parameter | Description |
---|---|
object | Object类型 指定需要遍历的对象或数组。 |
callback | Function类型 指定的用于循环执行的函数。 |
示例
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
div {
color: blue;
}
div#five {
color: red;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
$(function () {
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
$.each( arr, function( i, val ) {
$( "#" + val ).text( "我的是 " + val + "." );
// 在 "three" 之后将停止运行
return ( val !== "three" );
});
$.each( obj, function( i, val ) {
$( "#" + i ).append( document.createTextNode( " - " + val ) );
});
})
</script>
</body>
</html>