简体   繁体   English

动态jQuery UI datepicker元素

[英]Dynamic jQuery UI datepicker elements

I am using the jQuery UI datepicker function to create a number of date fields in my html form. 我使用jQuery UI日期选择器功能在我的HTML表单创建一个数日期字段。

I am using the following code to get any input field with a 'datepicker' class to work: 我正在使用以下代码来获取带有“ datepicker”类的所有输入字段,以使其正常工作:

$('.datepicker').each(function() {
    var id = $(this).attr('id').split('_')[0];

    if ($('#'+id+'_value').val()) { 
        var initialdate = new Date($('#'+id+'_value').val());
    }
    else {
        var initialdate = new Date();
    }

    $(this).val($.datepicker.formatDate('DD, d MM, yy', initialdate));
    $('#'+$(this).attr('id').split('_')[0]+'_value').val($.datepicker.formatDate('yy-mm-dd', initialdate));
    $(this).datepicker({
                        'dateFormat': 'DD, d MM, yy',
                        'altField': '#'+id+'_value',
                        'altFormat': 'yy-mm-dd' 
    });
});

However, I'm also using some other javascript to clone a span which contains several form elements. 但是,我还使用其他一些JavaScript来克隆包含多个表单元素的跨度。 When the new elements are created, the datepicker function does not work. 创建新元素时,日期选择器功能不起作用。

What can I do to make the new ones work like the existing ones? 我怎样做才能使新的像现有的一样工作?

Any advice appreciated. 任何建议表示赞赏。

Thanks. 谢谢。

As you are probably calling that iteration on document creation, items added to the DOM later are not instantiated as new datepickers, so you would have to explicitly call .datepicker() on each of the newly added elements you wish to enable datepicker on. 正如您可能在创建文档时调用该迭代一样,以后添加到DOM的项不会被实例化为新的datepicker,因此您必须在希望启用datepicker的每个新添加的元素上显式调用.datepicker()。

Basically, move the code from the iterator above to its own function, then do: 基本上,将代码从上面的迭代器移至其自己的函数,然后执行以下操作:

$('.datepicker').each(myDatePickerFunction($(this));

And call the same function on the elements you add later. 并在以后添加的元素上调用相同的函数。

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

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