我正在一个项目中,在向动态添加的表行添加datetimepicker时遇到困难。我已将datetimepicker添加到静态表行中,它对它们工作正常,但不适用于动态添加的表行。
我遵循的有关datetimepicker的教程
https://eonasdan.github.io/bootstrap-datetimepicker/
我尝试的代码:我正在克隆隐藏的行。
行克隆功能:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
隐藏的td的HTML:
<td> <div style="position: relative"> <input class = "form-control" type= "text" name = "datepicker"
id= "datetime"></div> </td>
答案 0 :(得分:0)
我的猜测...是该元素必须在DOM中才能实例化datetimepicker ...
因此将克隆ID保留在变量中,以便可以使用它来查找正确的datepicker元素。追加行。最后实例化datetimepicker。
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
var cloneID = parseInt(max)+1;
$clone.attr('id', cloneId);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
// Use the clone ID to instantiate datetimepicker
$("#cloneID").find("[name='datepicker']").datetimepicker();
//submitting form after row clone
submitForm();
});