Jquery中的$().each,$.each的區別

在jquery中,遍歷對象和數組,常常會用到$().each和$.each(),兩個方法。兩個方法是有區別的,從而這兩個方法在針對不一樣的操做上,顯示了各自的特色。jquery

$().each,對於這個方法,在dom處理上面用的較多。若是頁面有多個input標籤類型爲checkbox,對於這時用$().each來處理多個checkbook,例如:數組

$(「input[name=’ch’]」).each(function(i){
if($(this).attr(‘checked’)==true)
{
//一些操做代碼dom

}函數

回調函數是能夠傳遞參數,i就爲遍歷的索引。this

對於遍歷一個數組,用$.each()來處理,簡直爽到了極點。例如:對象

$.each([{「name」:」limeng」,」email」:」xfjylimeng」},{「name」:」hehe」,」email」:」xfjylimeng」},function(i,n)
{
alert(「索引:」+i,」對應值爲:」+n.name);
});索引

參數i爲遍歷索引值,n爲當前的遍歷對象.three

 

var arr1 = [ 「one」, 「two」, 「three」, 「four」, 「five」 ];
$.each(arr1, function(){
alert(this);
});
輸出:one   two  three  four   five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
輸出:1   4   7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
輸出:1   2  3  4  5input

相關文章
相關標籤/搜索