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">


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