each(callback):每个匹配的元素都会执行该函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<input type="checkbox" name="hobby" id="1" value="1" checked="checked" />篮球
<input type="checkbox" name="hobby" id="2" value="2" />乒乓球
<input type="checkbox" name="hobby" id="3" value="3" />足球
<script type="text/javascript">
$("[name='hobby']").each(function(){
console.log(this);
});
</script>
</body>
</html>
此时:参数实参所指函数中的this 指代的是 DOM 对象而非 jQuery 对象; 如果在函数中使用jQuery对象,可以通过 $(this) 方式进行转换。
each(object[, callback]):用于遍历对象(可以是jQuery对象)和数组,其中object表示待遍历的jQuery对象或数组;callback表示每个成员/元素执行的回调函数,
如下例子:
遍历数组:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
var names=["jim","tom"];
$.each(names,function(i, name){
console.log(i+":"+name);
});
</script>
</body>
</html>
遍历jQuery对象:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<input type="checkbox" name="hobby" id="1" value="1" checked="checked" />篮球
<input type="checkbox" name="hobby" id="2" value="2" />乒乓球
<input type="checkbox" name="hobby" id="3" value="3" />足球
<script type="text/javascript">
$("[name='hobby']").each(function(){
console.log(this);
});
$.each($("[ name='hobby']"),function(i,name){
console.log(i+":"+name);
});
</script>
</body>
</html>