jquery里面的循环的用法 下面提一下jQuery的each方法的几种常用的用法 Js代码 var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){ alert(this); }); //上面这个each输出的结果分别为:one,two,three,four
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); }); //其实arr1为一个二维数组,item相当于取每一个一维数组, //item[0]相对于取每一个一维数组里的弟一个值 //所以上面这个each输出分别为:1 4 7
var obj = { one:1, two:2, three:3, four:4}; $.each(obj, function(key, val) { alert(obj[key]); }); //这个each就有更厉害了,能循环每一个属性 //输出结果为:1 2 3 4
<script type="text/javascript"> $(function(){ var con=[ { "image1":"img/1524880084962.jpg", "shopName":"黑花生(100g*15袋/盒)", "price":190, "markPrice":200 }, { "image1":"img/1524879960117.jpg", "shopName":"黑花生(100g*15袋/盒)", "price":190, "markPrice":200 }, { "image1":"img/1524879605807.jpg", "shopName":"黑花生(100g*15袋/盒)", "price":190, "markPrice":200 }, { "image1":"img/1524879181488.jpg", "shopName":"黑花生(100g*15袋/盒)", "price":190, "markPrice":200 } ] var html=""; $.each(con, function(k,v) {//这里的函数参数是键值对的形式,k代表键名,v代表值 html+='<li class="shopBox">'+ '<div class="shopImg"><img src='+con[k].image1+'/></div>'+ '<div class="shopListName">'+con[k].shopName+'</div>'+ '<div class="shopPrice">'+ '<span class="price">¥'+con[k].price+'</span>'+ '<span class="marketPrice">¥'+con[k].markPrice+'</span>'+ '</div>'+ '</li>' }); $(".shop_box").append(html); }) </script>
<script> var a = { "sys_bb": [ { "menu_name": "教务处", "menus": [ { "menu_name": "张明" }, { "menu_name": "王明" } ] }, { "menu_name": "办公室", "menus": [ { "menu_name": "刘处" }, { "menu_name": "小王" }, { "menu_name": "张三" } ] } ], "sys_cw": [ { "menu_name": "财务处", "menus": [ { "menu_name": "王虎" } ] } ] }; $(function () { $.each(a.sys_bb, function (i, n) { $("#Div").append(a.sys_bb[i].menu_name + "<br>"); $.each(a.sys_bb[i].menus, function (i, n) { $("#Div").append(" " + n.menu_name + "<br>"); }); }); $.each(a.sys_cw, function (i, n) { $("#Div").append(a.sys_cw[i].menu_name + "<br>"); $.each(a.sys_cw[i].menus, function (i, n) { $("#Div").append(" " + n.menu_name + "<br>") }); }); }); </script>