简体   繁体   English

使用datepickers复制的html元素上的jQuery UI Datepicker

[英]jQuery UI Datepicker on copied html elements with datepickers

I have a form in which a user can add a set of fields dynamically as needed. 我有一种表单,用户可以在其中根据需要动态添加一组字段。 The code for that just copies the last entry and increments the counters in the field names (work around for my question here ) The code follows: 该代码仅复制最后一个条目并增加字段名称中的计数器(在这里解决我的问题),代码如下:

$("#addBeneficiary").click(function(e) {
    e.preventDefault();
    var beneficiary = $(".beneficiary:last").clone();
    var count = parseInt(beneficiary.find("input:first").attr("id").match(/\d+/), 10);
    beneficiary.find("input").each(function(indx, element) { 
        var name = $(element).attr('name').replace(count, count+1),
            id   = $(element).attr('id').replace(count, count+1);
        $(element).attr('name', name);
        $(element).attr('id', id);
        $(element).val(''); 
    });

    $("#beneficiaries").append(beneficiary);
    datepicker();
});

The last line datepicker(); 最后一行datepicker(); is just a function that finds all input.datepicker and executes the jQuery UI datepicker() function to add date pickers to those fields. 只是找到所有input.datepicker并执行jQuery UI datepicker()函数的功能,以将日期选择器添加到这些字段。 The problem I'm running into is this; 我遇到的问题是这个; the datepicker works fine on the first fields, but when they are dynamically added the datepicker doesn't pop up for the new fields. datepicker在第一个字段上可以正常工作,但是当动态添加日期选择器时,不会为新字段弹出日期选择器。

I've traced the code execution with logging statements to ensure my datepicker() function is called after the append and that all works. 我已经用日志记录语句跟踪了代码的执行情况,以确保在添加之后调用datepicker()函数,并且一切正常。 Here is my datepicker() code 这是我的datepicker()代码

var datepicker = function() {
    $("input.datepicker").datepicker();
};

Does anyone know why this is not working as expected? 有谁知道为什么这没有按预期工作?

My guess is that it has to do with the clone. 我的猜测是它与克隆有关。 I know you can accomplish this with a live datepicker activation for they dynamically added elements. 我知道您可以通过动态日期选择器激活来完成此操作,因为它们可以动态添加元素。 Try out this jsfiddle . 试试这个jsfiddle

$("input.datepicker").live('focus', function(){
    var $this = $(this);
    if(!$this.data('datepicker')) $this.datepicker();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM