在按钮单击时将datepicker附加到新行的列

时间:2013-06-24 17:40:55

标签: javascript jquery datepicker html-table onclick

我正在尝试在按钮点击上添加新行。在我的新行中有一个Textbox,我想用它绑定datepicker但不能。请帮我解决这个问题。
HTML代码

<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>

Java脚本:

$(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
}

编辑:当我添加代码“$('。date',rowClone).datepicker();”时。有一个奇怪的问题。 Seq1:添加行=&gt;点击newRow的文本框,弹出日历,一切正常 Seq2:1。点击原始行文本框的文本框,没有任何内容弹出。
 2.单击文档,然后尝试原始行的文本框,然后弹出日历 3.添加新行 4.现在点击新行的文本框,日历从不会弹出来选择日期。

非常感谢任何帮助。该方案的JSFiddle如下:

http://jsfiddle.net/wAyhm/9/

对于工作解决方案请按照以下链接: Adding new row, binding of datepicker to cloumn works in weird manner

2 个答案:

答案 0 :(得分:1)

使用rowClone作为选择器中的上下文,您可以抓取.date元素以应用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();
}

答案 1 :(得分:0)

$('.datepicker').on('focusin', '.datepicker', function(e) {
    $(this).datepicker();
});