遍历节点:
使用each(callback)方法来遍历元素
经典用法:
$(selector).each(function(index,element){
…
});
美元符号(selector):返回的是一个集合(伪数组)
index:当前遍历节点的索引
element:DOM元素对象
使用jquery方法或者属性时,需要转换为jquery对象 —>$(element)
或者使用$(this) -->当前遍历节点对象
方式二:
$.each(array,function(index,element){
…
});
主要用来遍历数组、对象、集合,处理数据
Demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Jquery之元素操作</title>
<style>
.outer{
margin-bottom: 100px;
}
</style>
<script src="../../js/jquery.min.js"></script>
<script>
$(function(){
var sum=0;
var sumElement=$('#sum');
$('.outer>div').each(function(index,element){
console.log("index:"+index+"--->"+$(element));
console.log($(this));//获取当前元素
$(this).css('color',colors[index]);
var val=Number($(this).text());
sum+=val;
});
sumElement.text(sum);
console.log("------------------------------------------");
//($('.outer2>div') -->返回的是一伪数组
//遍历数组
$.each($('.outer2>div'),function(index,element){
console.log(index);
console.log(element);
});
//遍历对象:每次循环取出一键值对(key:value) 属性名:属性值
var person={name:"jack bryant",age:25,address:"XuZhou"};
$.each(person,function(key,value){
console.log(key+":"+value);
});
console.log("------------------------------------------");
//使用js中的 for in循环 遍历对象
//每次循环取出一键值对(key:value)中属性名 key
for(var key in person){
console.log(key+":"+person[key]);
}
});
</script>
</head>
<body>
<div class="outer">
<div>10</div>
<div>20</div>
<div>30</div>
<p>总和:</p><span id="sum"></span>
</div>
<div class="outer2">
<div>40</div>
<div>50</div>
<div>80</div>
</div>
</body>
</html>