JQuery的$().each和$.each

一、$().each,對於這個方法,在dom處理上面用的較多。

如果頁面有多個input標籤類型爲checkbox,對於這時用$().each來處理多個checkbox。作爲批量操作非常方便傳參數。

var checkedItems =new Array();
$("input[name='ids[]']:checked").each(function(i){
	checkedItems.push($(this).val());
});
if(checkedItems.length==0){
	alert('至少要選一條記錄');
	return false;
}

each裏面是一個回調函數,可以把i作爲參數傳進去,對應的就是選擇的dom的索引值。

二、$.each()主要用於數組或對象處理。

使用格式$.each(obj,function(){.....});

實例1、

var arr=[{"name":"huangbaoying","email":"[email protected]"},{"name":"hby","email":"[email protected]"}];
$.each(arr,function(i,n){
	document.writeln("索引值"+i+"姓名爲"+n.name+"郵箱爲"+n.email);
})
//索引值0姓名爲huangbaoying郵箱爲[email protected]索引值1姓名爲hby郵箱爲[email protected]
實例2、

var arr=["a","b","c","d"];
$.each(arr,function(i){
	document.writeln(i+this);
})
//0a1b2c3

實例3、

$.each($("input:hidden"),function(i,val){
	document.writeln(val.name);
	document.writeln(val.value);
})

<input type="hidden" name="a" value="111">
<input type="hidden" name="b" value="222">
<input type="hidden" name="c" value="333">
<input type="hidden" name="d" value="444">


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章