1. 程式人生 > >Jquery 遍歷數組之$().each方法與$.each()方法介紹

Jquery 遍歷數組之$().each方法與$.each()方法介紹

gre 一個 var 頁面 his alert index blog .cn

$().each()

對於這個方法,在dom處理上用的比較多,如果一個html頁面上面有多個checkbox,這時用$().each來處理checkbox是比較不錯的;

$("input[type=‘checkbox‘]").each(function(i){
   $(this).attr("checked",true);
});

回調函數裏面的i在此處代表input集合傳遞過去的索引(也就是正在遍歷的input元素的索引);

但是這段代碼只用到了input集合的索引

技術分享圖片
<head>
    <title></title>
    <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(‘input:hidden‘).each(function (index, obj) {
                alert(obj.name + "..." + obj.value);
            });
        });
    </script>
</head>
<body>
<input type="hidden" value="1" name="a"/>
<input type="hidden" value="2" name="b"/>
<input type="hidden" value="3" name="c"/>
</body>
技術分享圖片

上面這段代碼用到了input集合的索引,有用到了input集合的dom對象,可以通過該對象,拿到其對應的屬性如:name,value等;

$.each()方法

1. 該方法處理一維數組,代碼如下:

$.each(["aaa","bbb","ccc"],function(index,value){
     alert(i+"..."+value);
});

結果是輸出 0...aaa 1...bbb 2...ccc

2.該方法處理二維數組,代碼如下:

技術分享圖片
        $(function () {
            $.each([["aaa", "bbb", "ccc"], ["ddd", "eee", "fff"], ["ggg", "hhh", "iii"]], function (index, item) {
                alert(index + "..." + item);
                //輸出0...aaa,bbb,ccc  1...ddd,eee,fff  2...ggg,hhh,iii   這時的index為數組下標,item相當於取這二維數組中的每一個數組
                $.each(item, function (index, itemobj) {
                    alert(index + "....." + itemobj);
                });
            });
            //輸出0...aaa,bbb,ccc  0...aaa 1...bbb 2...cccc  1...ddd,eee,fff  0...ddd 1...eee 2...fff  2...ggg,hhh,iii 0...ggg 1...hhh 2...iii
        });
技術分享圖片

3.該方法處理json數組,代碼如下:

技術分享圖片
        $(function () {
            var json = [{ name: "張三", sex: "男" }, { name: "李四", sex: "女" }, { name: "王五", sex: "gay"}];  //自定義一個json數組
            $.each(json, function (index, obj) {
                alert(index + "..." + obj.name+"..."+obj.sex);
            });
        });
技術分享圖片

json為後臺傳遞過來的json數組,each遍歷該數組,index通常為數組裏面對象的索引,而obj為當前遍歷到的對象

轉載於:https://www.cnblogs.com/GreenLeaves/p/5640842.html

Jquery 遍歷數組之$().each方法與$.each()方法介紹