好的,所以我尝试动态生成表单字段,然后添加一个日期选择器,但每次添加新的日期选择器时,它都会删除表单上所有以前的日期选择器。
class morePayments {
constructor() {
this.state = 0;
};
changeState() {
this.state = this.state + 1;
if (this.state <= 5) {
var dummy = '<fieldset class="form-group row">' +
'<label class="col-xs-2 text-right control-label">Amount:</label>' +
'<div class="col-xs-4"><input type="text" id="payment[]" name="payment[]"></div>' +
'<div class="col-xs-5">' +
'<div class="input-group">' +
'<span class="input-group-addon"><i class="fa fa-calendar"></i></span>' +
'<input type="text" id="paymentdate-' +
this.state + '" name="paymentdate-' + this.state + '" />' +
'</div>' +
'</div>' +
'</fieldset>'
document.getElementById('modal-body-payment').innerHTML += dummy;
$( "#paymentdate-" + this.state ).datepicker({
dateFormat: "dd-mm-yy"
});
}
};
};
state = new morePayments();
答案 0 :(得分:1)
问题在于这一行:
document.getElementById('modal-body-payment').innerHTML += dummy;
当你重写innerHTML时,意味着DOM树完全重建,这当然意味着你丢失了所有先前绑定的事件处理程序。
改为添加新内容:
$('#modal-body-payment').append(dummy);