1 $.each()对数据的处理:
语法:$.each(data,function(index,value))
1.1eg:对数组数据的处理:
<body>
<p></p>
<script>
var arr1=new Array("a","b","c","de");
var tmps="";
fun1();
function fun1(){
$.each(arr1,
function(i,val) {
tmps+=i+"----"+val+"<br/>";
});
$("p").html(tmps);
};
</script>
</body>
输出结果:
0----a
1----b
2----c
3----de
1.2eg:对json数据处理
var
json1={key1:"a","9527":"b","key3":"c"};
var tmps="";var hang1="------";var
hang2="<br/>";
$.each(json1,
function(key,value) {
tmps+=key+hang1+value+hang2;
});
$("p").html(tmps);
输出:
var
json2={key1:"a","9527":"b","key3":"c"};
var tmps="";var hang1="------";var
hang2="<br/>";
$.each(json2,
function(key,value) {
tmps+=key+hang1+value+hang2;
});
$("p").html(tmps);
1.3eg: 对数组对象的处理
var json4=[{name:"n1",age:"18"},{name:"jim",age:"20"},{name:'amy',"age":16}];
var tmps="";var hang1="------";var hang2="<br/>";
$.each(json4,
function(key,vale) {
tmps+=key+hang1+vale.name+hang2;
});
$("p").html(tmps);
2 对DOM的处理:
在遍历DOM时,通常用$(selector).each(function(index,element))函数;
也可以用$.each(each(function(index,element))函数;
eg:
<p></p>
<input name="dm" type="hidden" value="a" />
<input name="dm" type="hidden" value="b" />
<input name="dm" type="hidden" value="c" />
<input name="dm" type="hidden" value="d"/>
<script>
var tmps="";
$.each($("[name='dm']"), function(i,val) {
tmps+=i+"------"+val.name+"-----"+val.value+"<br/>";
});
$("p").html(tmps);
</script>
也可以这样写:
<body>
<p></p>
<input name="dm" type="hidden" value="a" />
<input name="dm" type="hidden" value="b" />
<input name="dm" type="hidden" value="c" />
<input name="dm" type="hidden" value="d"/>
<script>
var tmps="";
$("[name='dm']").each( function(i,val) {
tmps+=i+"------"+val.name+"-----"+val.value+"<br/>";
});
$("p").html(tmps);
</script>
</body>
来源:https://www.cnblogs.com/zoood/p/10938846.html