您的位置:首頁技術文章
文章詳情頁

jQuery.each() 函數遍歷指定的對象和數組

瀏覽:6日期:2022-06-09 13:08:38

jQuery.each()函數用于遍歷指定的對象和數組。

語法一: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>
 //加法運算
 varsum=0;
 $("div").each(function(index,domEle){
  sum+=parseInt($(domEle).text());
 })
 console.log(sum); 

</script>


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

</script>


3、遍歷數組
<script>
 //遍歷數組
 vararr=["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>
標簽: JavaScript JQ
相關文章:
国产综合久久一区二区三区