有這麼一段代碼:
var datas=[];
var data={};
var i=0;
$(".baby-panel").each(function(){
var baby_id=$(this).children(".babyid").attr("baby_id");
var baby_name=$(this).children(".babyname").find("input[name='baby"+i+"_name']").val().trim();
var baby_sex=$(this).children(".babysex").find("input[type=radio]:checked").val();
var baby_birth=$(this).children(".babybirth").find(".form-control").val();
data["id"]=baby_id;
data["name"]=baby_name;
data["sex"]=baby_sex;
data["birth"]=baby_birth;
datas[i]=data;
i++;
});
**問**:如何循環將data的數據添加到datas中,現在datas的數據都是data的最後一條記錄。
例如:data={["id":1,"name":1,"sex":1,"birth":2014-05-05],["id":2,"name":2,"sex":2,"birth":2014-06-05]}
經過each()遍歷後,datas的輸出**卻是**[{"id":"2","name":"2","sex":"2","birth":"2014-06-05"},{"id":"2","name":"2","sex":"2","birth":"2014-06-05"}],
而不是:[{"id":"1","name":"1","sex":"1","birth":"2014-05-05"},{"id":"2","name":"2","sex":"2","birth":"2014-06-05"}]
var datas=[];
//var data={};//把data放到循環裡面,否則會覆蓋
var i=0;
$(".baby-panel").each(function(){
** var data={};//每次新建一個data**
var baby_id=$(this).children(".babyid").attr("baby_id");
var baby_name=$(this).children(".babyname").find("input[name='baby"+i+"_name']").val().trim();
var baby_sex=$(this).children(".babysex").find("input[type=radio]:checked").val();
var baby_birth=$(this).children(".babybirth").find(".form-control").val();
data["id"]=baby_id;
data["name"]=baby_name;
data["sex"]=baby_sex;
data["birth"]=baby_birth;
** datas.push(data);**
i++;
});