javascript - 添加新行,将日期选择器绑定(bind)到列以奇怪的方式工作

标签 javascript jquery html-table datepicker jquery-ui-datepicker

我正在尝试在单击按钮时添加新行。在我的新行中有一个文本框,我想绑定(bind)日期选择器但无法绑定(bind)。请帮我解决这个问题。

<table>
     <tr>
     <td><button type="button" onClick ="addRow(this)">Add</button></td>
     </tr>
     <tr>
     <td><input type="text" name="installDate" value="" class ="date"/> </td>        
     </tr>
</table>

JavaScript

$(document).on('click', function() {
$('.date').each(function() {
        $(this).datepicker();
});
});

function addRow(btn) {         
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var rowCount = table.rows.length;
    var lastRow = table.rows[rowCount - 1];
    var rowClone = lastRow.cloneNode(true);
    table.appendChild(rowClone);
    $('.date', rowClone).datepicker(); // Code to fix the problem
}

Seq1:添加行=>单击newRow的文本框,弹出日历,一切正常。

序列2: 1. 单击文档,然后尝试原始行的文本框,然后弹出日历。 2. 添加新行。 3.现在单击新行的文本框,日历不会弹出来选择日期。

附上 JSFiddle 以供引用 http://jsfiddle.net/wAyhm/9/

最佳答案

这就是您要找的:

How to clone elements that have been bound by a jQuery UI Widget?

工作 fiddle :

http://jsfiddle.net/Meligy/DKtA6/6/

window. addRow = function addRow(btn) {         
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var rowCount = table.rows.length;
    var lastRow = table.rows[rowCount - 1];
    var lastDatePicker = $('.date', lastRow);
    var rowClone = $(lastRow).clone(true);
    var datePickerClone = $('.date', rowClone);
    var datePickerCloneId = 'test-id' + rowCount;
    datePickerClone.data( "datepicker", 
        $.extend( true, {}, lastDatePicker.data("datepicker") ) 
    ).attr('id', datePickerCloneId);
    datePickerClone.data('datepicker').input = datePickerClone;
    datePickerClone.data('datepicker').id = datePickerCloneId;
    $(table).append(rowClone);
    datePickerClone.datepicker();
}

关于javascript - 添加新行,将日期选择器绑定(bind)到列以奇怪的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286100/

相关文章:

javascript - Chart.js 绘制时间序列

javascript - 从外部 JSON 文件获取文件内容

jquery - 允许用户创建 MySQL 过滤器时转义危险代码

html - 有没有办法专门设计左侧所有表格单元格或特定列的样式?

html - 在具有容器大小的两个其他元素之间生长一个元素

html - 表格单元格问题中的图像?

javascript - JS在生成的ajax div中添加文本

javascript - 在 CSS 中重复图像的一部分

Jquery onclick div 上

来自帖子的 Jquery 响应