一、遍歷元素
jquery隱式迭代是對同一類元素做了同樣的操作。如果想要給同一類元素做不同的操作,就需要用到遍歷
語法一:each方法
$("div").each(function(index,domEle){
//回調函數第一個參數(index)一定是索引號
//回調函數第二個參數(domEle)一定是dom元素
……
})
1、each()方法遍歷匹配的每一個元素,主要用於DOM處理。each每一個
2、里面的回調函數有兩個參數:index是每個元素的索引號,demEle是每個DOM元素對象
3、所以想要使用jquery方法,需要給這個dom元素轉換成jquery對象$(domEle)
語法二:$.each()方法
$.each(object,function(index,element){ //object為需要被遍歷的對象 //里面的函數有2個參數:index是每個元素的索引號;element遍歷內容 …… })
1、$.each()方法可以用來遍歷任何的對象。主要用於數據的處理,比如數組、對象
2、里面的函數有2個參數:index是每個元素的索引號;element遍歷內容
二、舉例
<body> <div>1</div> <div>2</div> <div>3</div> </body>
1、求和
<script>
//加法運算
var sum = 0;
$("div").each(function(index, domEle) {
sum += parseInt($(domEle).text());
})
console.log(sum);
</script>

2、改變樣式
<script>
//更換樣式
var arr = ['red', 'green', 'blue']
$("div").each(function(index, domEle) {
//需要把dom元素先轉換為jquery對象才可以使用jQuery的方法
$(domEle).css("color", arr[index]);
})
</script>

3、遍歷數組、
<script>
//遍歷數組
var arr = ['red', 'green', 'blue']
$.each(arr, function(index, ele) {
console.log(index);
console.log(ele);
})
</script>

4、遍歷對象
<script>
//遍歷數組
$.each({
name: "andy",
age: 18
}, function(i, ele) {
console.log(i);//輸出對象包含的屬性
console.log(ele);//輸出屬性對應的屬性值
})
</script>

