【问题标题】:Adding new row, binding of datepicker to cloumn works in weird manner添加新行,将日期选择器绑定到列以奇怪的方式工作
【发布时间】:2017-11-19 04:26:29
【问题描述】:

我正在尝试在按钮单击时添加新行。在我的新行中,有一个文本框,我想与它绑定 datepicker 但无法绑定。请帮我解决这个问题。

<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: Add Row => 点击newRow的文本框,弹出日历,一切正常。

序列2: 1、点击文档,然后在原行的文本框上试一下,会弹出日历。 2. 添加新行。 3.现在点击新行的文本框,日历永远不会弹出选择日期。

附加 JSFiddle 以供参考 http://jsfiddle.net/wAyhm/9/

【问题讨论】:

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


    【解决方案1】:

    这就是你要找的:

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

    工作小提琴:

    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();
    }
    

    【讨论】:

    • 感谢您的帮助。实际上我需要克隆列,相同的解决方案是否也适用于列克隆?
    • 嗯,它应该,重要的部分是在你克隆之后。您复制 data 属性,并创建一个唯一 ID,然后将 id 和此 input 属性映射到新的文本框克隆。
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2021-02-28
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多