示例代码:
<input type="text" class="form-control form-control-sm form_datetime" id="emigrant_date" name="emigrant_date" autocomplete="off">
datepicker/datetimepicker的默认触发方式:
$(".form_datetime" ).datepicker();
但是在该应用中,我需要动态创建一些input,
$("#add").on("click",function(){
var num = $("#educational_background_number").val();
var htm='<tr>'
+'<td><input type="text" class="form-control form-control-sm form_datetime" id="emigrant_date" name="emigrant_date" autocomplete="off"></td>'
+'<td><input type="text" class="form-control form-control-sm form_datetime" id="emigrant_date" name="emigrant_date" autocomplete="off"></td>'
+'<td><input type="text" class="form-control form-control-sm" id="emigrant_date" name="emigrant_date" autocomplete="off"></td>'
+'<td><input type="text" class="form-control form-control-sm" id="emigrant_date" name="emigrant_date" autocomplete="off"></td>'
+'<td><a href="javascript:;" class="btn btn-default btn-sm" onclick="remove(this)">delete</a></td>'
+'</tr>';
$("#educational_background_table tbody").append(htm);
})
结果发现动态创建的input使用默认的触发方式无效,无法弹出时间或日期选择框,解决是将默认的触发代码换成下面的代码:
$('body').on('focus',".form_datetime", function(){
$(this).datepicker();
});
如果上面的代码无效,那么就把body换成document即可:
$('document').on('focus',".form_datetime", function(){
$(this).datepicker();
});