定义和用法
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>
案例看完了,你学会了吗?记得收藏起来哦,不然会找不到的!