文章詳情頁
jQuery.each() 函數(shù)遍歷指定的對象和數(shù)組
瀏覽:4日期:2022-06-09 13:08:38
jQuery.each()函數(shù)用于遍歷指定的對象和數(shù)組。
語法一:each方法
$("div").each(function(index,domEle){//回調(diào)函數(shù)第一個(gè)參數(shù)(index)一定是索引號
//回調(diào)函數(shù)第二個(gè)參數(shù)(domEle)一定是dom元素
……
})
1、each()方法遍歷匹配的每一個(gè)元素,主要用于DOM處理。each每一個(gè)
2、里面的回調(diào)函數(shù)有兩個(gè)參數(shù):index是每個(gè)元素的索引號,demEle是每個(gè)DOM元素對象
3、所以想要使用jquery方法,需要給這個(gè)dom元素轉(zhuǎn)換成jquery對象$(domEle)
語法二:$.each()方法
$.each(object,function(index,element){
//object為需要被遍歷的對象
//里面的函數(shù)有2個(gè)參數(shù):index是每個(gè)元素的索引號;element遍歷內(nèi)容
……
})
1、$.each()方法可以用來遍歷任何的對象。主要用于數(shù)據(jù)的處理,比如數(shù)組、對象
2、里面的函數(shù)有2個(gè)參數(shù):index是每個(gè)元素的索引號;element遍歷內(nèi)容
二、舉例
<body>
<div>1</div>
<div>2</div>
<div>3</div>
</body>
1、求和
<script>
//加法運(yùn)算
varsum=0;
$("div").each(function(index,domEle){
sum+=parseInt($(domEle).text());
})
console.log(sum);
</script>
<script>
//更換樣式
vararr=["red","green","blue"]
$("div").each(function(index,domEle){ //需要把dom元素先轉(zhuǎn)換為jquery對象才可以使用jQuery的方法
$(domEle).css("color",arr[index]);
})
</script>
<script>
//遍歷數(shù)組
vararr=["red","green","blue"]
$.each(arr,function(index,ele){
console.log(index);
console.log(ele);
})
</script>
<script>
//遍歷數(shù)組
$.each({
name:"andy",
age:18
},function(i,ele){
console.log(i);//輸出對象包含的屬性
console.log(ele);//輸出屬性對應(yīng)的屬性值
})
</script>
標(biāo)簽:
JavaScript
JQ
相關(guān)文章:
排行榜
