我想将字段名称schedtimein更改为schedtimein加上x的值。例子schedtimein1,schedtimein2等等......我怎么能这样做,对不起我是新来的。
$(document).ready(function() {
var x = 1;
$('#meetingForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
schedtimein: {
verbose: false,
validators: {
notEmpty: {
message: 'The start time is required'
},
callback: {
message: 'The start time must be earlier then the end one',
callback: function(value, validator, $field) {
var schedtimeout = validator.getFieldElements('schedtimeout' + x).val();
if (schedtimeout === '') {
return true;
}
var startHour = parseInt(value.split(':')[0], 10),
startMinutes = parseInt(value.split(':')[1], 10),
endHour = parseInt(schedtimeout.split(':')[0], 10),
endMinutes = parseInt(schedtimeout.split(':')[1], 10);
if (startHour < endHour || (startHour == endHour && startMinutes < endMinutes)) {
// The end time is also valid
// So, we need to update its status
validator.updateStatus('schedtimeout' + x, validator.STATUS_VALID, 'callback');
return true;
}
return false;
}
}
}
},
schedtimeout: {
verbose: false,
validators: {
notEmpty: {
message: 'The end time is required'
},
callback: {
message: 'The end time must be later then the start one',
callback: function(value, validator, $field) {
var schedtimein = validator.getFieldElements('schedtimein' + x).val();
if (schedtimein == '') {
return true;
}
var startHour = parseInt(schedtimein.split(':')[0], 10),
startMinutes = parseInt(schedtimein.split(':')[1], 10),
endHour = parseInt(value.split(':')[0], 10),
endMinutes = parseInt(value.split(':')[1], 10);
if (endHour > startHour || (endHour == startHour && endMinutes > startMinutes)) {
// The start time is also valid
// So, we need to update its status
validator.updateStatus('schedtimein' + x, validator.STATUS_VALID, 'callback');
return true;
}
return false;
}
}
}
}
}
});
});
如何解决这个问题?如何将字段schedtimein的名称更改为schedtimein加上x的值,如schedtimein1,schedtimein2和...
答案 0 :(得分:0)
在删除对象文字var obj = {prop: value}
时,无法定义变量属性名称。但你可以在定义对象之后添加它们,就像这样......
var x = 1;
var fields = { // declare
schedtimeout: { ... }
};
fields['schedtimein' + x] = { ... }; // will add schedtimein1 to fields object.
// ...Add as many as you like with different values of { ... } (different values).
$('#meetingForm').formValidation({
framework: 'bootstrap',
icon: { ... },
fields: fields // now add your final object here.
});
编辑:正如下面的评论者所建议的那样,为了实现增量命名属性,你可以像这样循环它们......
for (; x <= numberOfProps; x++) {
fields['schedtimein' + x] = makeMyObjectBasedOnX(x);
}
makeMyObjectBasedOnX
函数根据传递的x
值返回一个对象,因此对于您定义的每个新属性都是唯一的。