1、遍历json对象
var obj = {id:"id",name:"name"}; $.each(obj,function(){ //此处this 指代当前遍历到的obj 的胞元素,即属性键值对 alert(this.id);//提示"id" }); var obj2 = [{id:"id1"},{id:"id2"}]; $.each(obj2,function(){ //此处this 指代当前遍历到的obj 的胞元素,即数组 alert(this.id);//提示"id1","id2" });
2、遍历元素对象
var selector = $("div"); $.each(eles,function(){ //此处this,指当前遍历到的eles 集合中div元素 })
举例如下:
<div class="mblock"> <input type="hidden" id="e" name="e" value="1" /> <input type="checkbox" name="SSStatus" id="SSStatus" /> <input type="checkbox" name="PFStatus" id="PFStatus" /> </div> <div class="mblock"> <input type="hidden" id="e2" name="e2" value="12" /> <input type="checkbox" name="SSStatus" id="SSStatus" /> <input type="checkbox" name="PFStatus" id="PFStatus" /> </div>
遍历上面的mblock对象,并把每一个mblock形成一个json对象数组,如:[{"EmployeeId":"1","SSStatus":1,"PFStatus":1},{"EmployeeId":"1","SSStatus":1,"PFStatus":1}]
方法如下:
$(function () { var mblockData = $(".mblock"); var postData = []; $.each(mblockData, function () { var empId = $(this).find("input[type='hidden']").val(); var cbData = $(this).find("input[type='checkbox']"); var arr = { "EmployeeId": empId }; $.each(cbData, function () { var keyName = $(this).attr("id"); var isChecked = $(this).is(':checked') ? 1 : 0; if (keyName=="SSStatus") arr.SSStatus = isChecked; if (keyName == "PFStatus") arr.PFStatus = isChecked; }) postData.push(arr); }) console.info(postData) })
这里用到怎样定义json数组及动态添加json值的方法
进一步解释如下(向数组中添加josn使用push):
var postData=[{"EmployeeId": "e2d6e69c", "SSStatus": 1,"PFStatus": 1}, {"EmployeeId": "b913cfe","SSStatus": 1,"PFStatus": 0}]; var arr ={"EmployeeId" : "abc","SSSTatus" : 1,"PFStatus":0}; postData.push(arr);
向json中添加元素使用如下方法:
var arr = { "EmployeeId": "abc"}; arr.SSStatus =1; arr.PFStatus = 0; 那么最终arr会形成:arr={"EmployeeId": "e2d6e69c", "SSStatus": 1,"PFStatus": 1}