我有一个具有这种结构的JavaScript对象:
var spouse = {
s_name: { value: spouse_name, label: "Name" },
s_nric: { value: spouse_nric_passport, label: "NRIC/Passport" },
s_dob: { value: spouse_date_of_birth, label: "Date of Birth" },
s_occupation: { value: spouse_occupation, label: "Occupation" },
s_weight: { value: spouse_weight, label: "Weight" },
s_height: { value: spouse_height, label: "Height" }
};
我目前正在这样迭代:
$.each(spouses, function(key, value) {
console.log(value);
$.each(value, function(int_key, int_value) {
console.log(int_key);
console.log(int_value.value);
console.log(int_value.label);
$("#spouse_data").append(
"<div class='col-sm-4'><label>" +
int_value.label +
"</label><input type='text' readonly class='form-control' value=" +
int_value.value +
"></div>"
);
});
});
这样做是将元素放入动态生成的html元素中。但是,我不确定如何放置删除功能。目前,如果我将它放在循环中,结构中的每一行数据都将包含一个删除函数而不是一般的删除函数。
如何更改此设置以便添加常规删除功能?或者有更好的方法将这个结构打印到屏幕上?
答案 0 :(得分:1)
您可以尝试以下方式:
var spousesArray = [{
s_name:{value:"spouse_name",label:"Name"},
s_nric:{value:"spouse_nric_passport",label:"NRIC/Passport"},
s_dob:{value:"spouse_date_of_birth",label:"Date of Birth"},
s_occupation:{value:"spouse_occupation",label:"Occupation"},
s_weight:{value:"spouse_weight",label:"Weight"},
s_height:{value:"spouse_height",label:"Height"}
},
{
s_name:{value:"spouse_name",label:"Name2"},
s_nric:{value:"spouse_nric_passport",label:"NRIC/Passport2"},
s_dob:{value:"spouse_date_of_birth",label:"Date of Birth2"},
s_occupation:{value:"spouse_occupation",label:"Occupation2"},
s_weight:{value:"spouse_weight",label:"Weight2"},
s_height:{value:"spouse_height",label:"Height2"}
}];
$.each(spousesArray, function(i, spouses){
var classN = 'parent-' + i;
var removeBtn = "<button onclick=remove('" +classN+ "')>Remove</button>";
$("#spouse_data").append("<div class='" +classN+ "'><div>")
$.each(spouses,function(key,value){
$("."+classN).append("<div class='col-sm-4'><label>"+value.label+"</label><input type='text' readonly class='form-control' value="+value.value+"></div>");
});
$("."+classN).append(removeBtn);
});
function remove(el){
$('.' + el).remove();
var position = el.split('-')[1];
spousesArray.splice(position,1);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spouse_data"></div>
&#13;