我对 JQuery $().find().each(function (i,e)...)
在$(e).find('option:selected').each()
中,所有条目均按预期记录到控制台中,但是,当添加到我创建的对象workstation.input {}
中时,它仅添加了最后选择的选项的最后一个值。
for (var i = 0; i < workstation.verifications.length; i++)
{
var verfication = workstation.verifications[i];
//defining the input field based on object "type" (See object def):
if (verfication.type == 'text')
{
var $input = $('<input/>').attr('type', verfication.type).attr('verfication-name', verfication.name).addClass('col form-control');
}
else if (verfication.type == 'choice')
{
var $input = $('<select/>').addClass('form-control')
.append($('<option/>').text('Good').attr("value", "Good"))
.append($('<option/>').text('N/A').attr("value", "N/A"))
.append($('<option/>').text('Bad').attr("value", "Bad"))
}
if (verfication['title'])
{
$formTable.append(
$('<div/>').text(verfication['title']).attr("id", 'workstationFormSectionHeader')
);
}
else if(!verfication['title'])
{
$formTable.append(
$('<div/>').addClass('row input-group').append($('<div/>').addClass('input-group-text col-sm-3').text(verfication.name))
.append($('<div/>').append($input).addClass('col')));
}
}
function get_form_data() {
var data = {workstation: []};
$('.workstation-form').each(function (i,e) {
var workstation = {
name: $(e).attr('workstation-name'),
input : {},
};
$(e).find('input').each(function(i,e2) {
//check for empty
if ($(e2).val() == "") {
return;
}
workstation.input[$(e2).attr('verfication-name')] = $(e2).val();
});
$(e).find('option:selected').each(function(i,e2){
if ($(e2).val() == "") {
return;
}
console.log($(e2));
workstation.input[$(e2).attr('verfication-name')] = $(e2).val();
})
data.workstation.push(workstation);
//data.controllers.push(controller);
});
return data;
}
以下是浏览器中的结果快照: Picture