jq 中的each遍歷
阿新 • • 發佈:2020-08-26
定義和用法
each() 方法為每個匹配元素規定要執行的函式。
提示:返回 false 可用於及早停止迴圈。
語法:
$(selector).each(function(index,element))
引數 | 描述 |
---|---|
function(index,element) | 必需。為每個匹配元素規定執行的函式。
|
案例1:
<!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>Document</title> <!-- 引入自己的jq檔案 --> <script src="..."></script> </head> <body> <script> $(function () {// 語法:$.each(obj,callback) $.each([12,23,34,45,56,67,78,89],function(index,value){ console.log(index+":"+value); }) }); </script> </body> </html>
案例2:
<!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>Document</title> <!-- 引入自己的jq檔案 --> <script src="..."></script> </head> <body> <script> $(function () { var obj={ "title":"中國", "src":"天安門", "age":"1000+" } // 遍歷物件 語法:$.each(物件名,function(鍵,值)) $.each(obj,function(key,val){ console.log(key+":"+val); }) }); </script> </body> </html>
案例3:
<!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>Document</title> <!-- 引入自己的jq檔案 --> <script src="..."></script> </head> <body> <script> $(function () { var json=[ { "title":"中國", "src":"北京", "age":"1000+" }, { "title":"美國", "src":"紐約", "age":"100+" },{ "title":"法國", "src":"巴黎", "age":"10+" }, ]; $.each(json,function(key,val){ // 遍歷成一組物件 $.each(val,function(i,value){ //遍歷一組中每一個物件 document.write(value+"<br>"); }) document.write("<hr/>") }) document.write("<br><br> 方法 2:<br><br>") $.each(json,function(i,ele){ $.each(ele,function(key,val){ document.write(key+":"+val+"<br>"); }) document.write("<br>") }) }); </script> </body> </html>
案例看完了,你學會了嗎?記得收藏起來哦,不然會找不到的!