问题
I am using the jQuery UI datepicker function to create a number of date fields in my html form.
I am using the following code to get any input field with a 'datepicker' class to work:
$('.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. 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.
回答1:
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.
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.
来源:https://stackoverflow.com/questions/12247902/dynamic-jquery-ui-datepicker-elements