[英]Datepicker not working in dynamically added row
When a row is added dynamically in a table, I don't get the datepicker,time spinner or the validations working for the second row. 当在表中动态添加行时,我没有得到datepicker,time spinner或第二行的验证。
my code for adding a row... 我添加行的代码......
function addRow(tableID){
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i = 0;i<colCount;i++){
var newccell = row.insertCell(i);
newcell.innerHTML = table.rows[i].cells[i].innerHTML;
}
}
and my code for the button is 我的按钮代码是
<input type = "button" onclick = "addRow(tableID)" name="+" value="+" id="add">
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation . 由于元素是动态添加的,因此无法将事件直接绑定到它们。因此,您必须使用事件委派 。
Syntax 句法
$( elements ).on( events, selector, data, handler );
function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i < colCount; i++) { var newccell = row.insertCell(i); newcell.innerHTML = table.rows[i].cells[i].innerHTML; } var $row = $(row); $row.find('input.sp').spinner(); //find element which you want to add spinner $row.find('input.dp').datepicker();//find element which you want to add datepicker }
You need to initialize the plugins/widgets for dynamic elements once the elements are rendered to the dom 一旦元素呈现为dom,您需要初始化动态元素的插件/小部件
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newccell = row.insertCell(i);
newcell.innerHTML = table.rows[i].cells[i].innerHTML;
}
var $row = $(row);
$row.find('input.spinner').spinner(){};//initialize spinner
$row.find('input.datepicker').datepicker({});//iniitailze datepicker etc
}
use clone 使用克隆
function addRow(tableID) {
var $table = $('#' + tableID),
$first = $table.find('tr').first();
var $row = $first.clone().appendTo($table)
$row.find('input.spinner').spinner() {};
$row.find('input.datepicker').datepicker({});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.