each()
each()方法常常和数组一起使用。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
</head>
<body>
<p>123</p>
<p>456</p>
<p>789</p>
</body>
<script>
$(function(){
var color=["red","aqua","yellow"];
$("p").each(function(index,domEle){
$(domEle).css("backgroundColor",color[index])
})
})
</script>
</html>
效果:
$.each()
1)先获取某个集合对象
2)遍历集合对象的每一个元素
(此处是将对象变为集合,而each()是将对象组成集合【所以要有多个或者直接为数组集合】)
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
</head>
<body>
<p>123</p>
<p>456</p>
<p>789</p>
</body>
<script>
$(function(){
var color=["red","aqua","yellow"];
$.each(color,function(index,ele){
console.log(index);
console.log(ele);
})
})
</script>
</html>
效果:
区别
$.each代码:
<script>
$(function(){
var object={
name:"andy",
age:18
}
$.each(object,function(index,ele){
console.log(index);
console.log(ele);
})
})
</script>
效果:
each() 代码:
<script>
$(function(){
var object={
name:"andy",
age:18
}
$(object).each(function(index,ele){
console.log(index);
console.log(ele);
})
})
</script>
效果: