JQuery的遍历
两种方式
-
jq对象.each(function()…); / $.each(object,function(){})(第二种写法)
语法:
jq对象.each(function(index,element){});
index:代表为下标(索引)
element:代表个体对象
-
for…of:jquery3.0之后才有了此方式,也就是for增强
语法:
for(元素对象 of 容器对象)
-
关于循环跳出,需要使用true(continue)或者false(break)
代码演示
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//js的遍历
$(function(){
//获取对象
var citys = $("#city li");
//js
// for(var i = 0 ; i < citys.length ;i++){
// alert(citys[i].innerHTML);
// }
/**
* jq遍历
* index代表为下标(索引)
* element元素个体对象
* 在判断语句中,如果element的值为北京,将会跳过
*/
// citys.each(function(index,element){
// // alert($(this).text());
// alert("i:"+index);
// if("北京" == $(element).html()){
// //当如果想跳出或者终止,在java中是continue和break,
// // 那么在jq中是true表示跳过,false表示终止
// return true;
// }
// alert("element:"+$(element).html());
// });
//第二种写法
// $.each(citys,function(){
// alert($(this).html());
// })
//jq3.0支持的增强for
// for(li of citys){
// alert($(li).html());
// }
});
</script>
</head>
<body>
<ul id="city">
<li>北京</li>
<li>上海</li>
<li>天津</li>
<li>重庆</li>
</ul>
</body>
</html>