jQuery目前是前端比较流行的JavaScript框架,循环遍历的场景工作中经常遇到,今天就对jQuery中的循环遍历做个总结。文章最后附综合案例代码。
第一:for、while、do while循环(所有开发语言通用的)用于遍历所有类型数组。
var hobby = document.getElementsByName('hobby');
for(var i=0;i<hobby.length;i++){
hobby[i].checked=sel;
}
while、do while略。
第二:for in (foreach)循环遍历
下面这段代码是向下拉列表中追加数据,用了两个for in。
window.onload=function(){
var proArr = [];
proArr['北京']=['朝阳区','昌平区','丰台区'];
proArr['山东']=['济南','青岛'];
proArr['河南']=['郑州','开封'];
var pro = document.getElementById('province');
for(var i in proArr){
pro.add(new Option(i,i));
}
document.getElementById('province').onchange=function(){
var city = document.getElementById('city');
city.innerHTML="<option> 选择城市</option>";
for(var i in proArr[this.value]){
city.add(new Option(proArr[this.value][i],proArr[this.value][i]));
}
}
}
第三:$.map和$().map遍历
官方说明:
将一组元素转换成其他数组(不论是否是元素数组)
你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。
举例:
$.map遍历数组:
$.map( [0,1,2], function(n){
return n > 0 ? n + 1 : null;
});
$().map遍历数组
$([0,1,2]).map(function(n){
alert(n + "h");
})
map常与join()一起使用,用与返回数组元素值拼接后的结果:
$.map遍历jquery对象:
//打印所选爱好
$("#map").click(function(){
var map=$("input[name='hobby']:checked").map(function(){
return $(this).val();
}).get().join(", ");
alert(map);
})
$().map遍历jQuery对象:
不拼接就是普通数组
$("#map2").click(function(){
var map=$.map( $("input[name='hobby']:checked"), function(n){
return $(n).val();
});
for(index in map){
alert(map[index]);
}
})
第三:$.each() 遍历:
通用遍历方法,可用于遍历对象和数组。
不同于遍历 jQuery 对象的 $().each() 方法,此方法可用于遍历任何对象。
回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。
如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
遍历数组
var arr=[0,1,2];
$.each( arr, function(i, n){
alert( "Item #" + i + ": " + n );
});
遍历json对象
jQuery提供了rializeArray()和rialize()方法来序列化表单元素。json常用与ajax提交数据。
$("#json").click(function(){
var fields = $(":checkbox:checked").serializeArray();
$.each( fields, function(i, field){
console.log(field);
alert(i+":"+field.name+":"+field.value);
});
})
遍历jquery对象
$("#each1").click(function(){
var $hobby=$("input[name='hobby']:checked");
$.each( $hobby, function(i, n){
alert($(n).val());
});
})
第四:$().each() 遍历:
以每一个匹配的元素作为上下文来执行一个函数。
意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整型)。 返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。
$("#each2").click(function(){
$("input[name='hobby']:checked").each(function(){
alert($(this).val());
})
})
综合案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
table{
border:1px solid;
}
table tr td{
border:1px solid;
height: 30px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
Date.prototype.format = function(fmt) { //日期格式化
var arr=['一','二','三','四','五','六','七'];
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds(), //毫秒
"w" : arr[this.getDay()-1]
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
function settime(){
var dt = new Date().format("yyyy-MM-dd hh:mm:ss 星期w");
document.getElementById('time').innerHTML=dt;
}
setInterval("settime()",1000);
// 全选
function selAll(){
var sel = document.getElementById('all').checked;
var hobby = document.getElementsByName('hobby');
for(var i=0;i<hobby.length;i++){
hobby[i].checked=sel;
}
}
function sel(){
var selAll = document.getElementById('all');
var hobby = document.getElementsByName('hobby');
var all=true;
for(var i=0;i<hobby.length;i++){
if(hobby[i].checked==false){
all=false;
break;
}
}
if(all){
selAll.checked=true;
}else{
selAll.checked=false;
}
}
window.onload=function(){
var proArr = [];
proArr['北京']=['朝阳区','昌平区','丰台区'];
proArr['山东']=['济南','青岛'];
proArr['河南']=['郑州','开封'];
var pro = document.getElementById('province');
for(var i in proArr){
pro.add(new Option(i,i));
}
//js 二级联动
document.getElementById('province').onchange=function(){
var city = document.getElementById('city');
city.innerHTML="<option> 选择城市</option>";
for(var i in proArr[this.value]){
city.add(new Option(proArr[this.value][i],proArr[this.value][i]));
}
}
//打印所选爱好
$("#map1").click(function(){
var map=$("input[name='hobby']:checked").map(function(){
return $(this).val();
}).get().join(", ");
alert(map);
})
$("#map2").click(function(){
var map=$.map( $("input[name='hobby']:checked"), function(n){
return $(n).val();
});
for(index in map){
alert(map[index]);
}
})
$("#json").click(function(){
var fields = $(":checkbox:checked").serializeArray();
$.each( fields, function(i, field){
console.log(field);
alert(i+":"+field.name+":"+field.value);
});
})
$("#each1").click(function(){
var $hobby=$("input[name='hobby']:checked");
$.each( $hobby, function(i, n){
alert($(n).val());
});
})
$("#each2").click(function(){
$("input[name='hobby']:checked").each(function(){
alert($(this).val());
})
})
}
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td>当前时间:</td>
<td id="time"></td>
</tr>
<tr>
<td><input type="checkbox" name='all' id="all" onclick="selAll()"/>爱好</td>
<td>
<input type="checkbox" name='hobby' onclick="sel()" value="足球"/>足球
<input type="checkbox" name='hobby' onclick="sel()" value="篮球"/>篮球
<input type="checkbox" name='hobby' onclick="sel()" value="网球"/>网球
</td>
</tr>
<tr>
<td>级联</td>
<td>
<select name="province" id='province'>
<option> 选择省</option>
</select>
<select name="city" id='city'>
<option> 选择城市</option>
</select>
</td>
</tr>
<tr>
<td>操作</td>
<td>
<button id="map1">爱好map</button>
<button id="map2">爱好map2</button>
<button id="each1">爱好each1</button>
<button id="each2">爱好each2</button>
<button id="json">爱好json</button>
</td>
</tr>
</table>
</body>
</html>
第五:jQuery是支持对jQuery数组对象的整体操作的,作用到数组中所有元素。
如下面全选的jQuery的实现方式:整个全选的过程,一个循环也没用到。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script >
$(function(){
$("#all").click(function(){//全选
$("input[name='hobby']").prop('checked',$(this).prop('checked'));
})
$("input[name='hobby']").click(function(){
var num = $("input[name='hobby']").length;
var num1 = $("input[name='hobby']:checked").length;
if(num==num1){
$("#all").prop('checked',true);
}else{
$("#all").prop('checked',false);
}
})
})
</script>
</head>
<body height='100'>
<table style="border: 1px solid;">
<tr>
<td><input type="checkbox" name='all' id="all" />爱好</td>
<td>
<input type="checkbox" name='hobby' value="足球"/>足球
<input type="checkbox" name='hobby' value="篮球"/>篮球
<input type="checkbox" name='hobby' value="网球"/>网球
</td>
</tr>
</table>
</body>
</html>
效果图: