问题
I have a datepicker input (call it X) on my page already. There's a button that when you click on it, it makes an ajax call and prints some html stuff on page. Inside that ajax response, there's another datepicker input (call it Y), which works when you open it on a standalone page, but inside the ajax call, the Y doesn't show the datepicker box (it works on X however).
The Y already has the "hasDatepicker" class, I've tried to remove it then recall the the datePicker method, but no luck. The only way I've managed to fix it, was to remove the "ui-datepicker-div" from page source and recall the datepicker on Y. But this time, X stops working!
What is wrong with this way of using datepicker? Any way that I can make both of them working correctly?
UPDATE: I've managed to fix this by running these two commands before ajax call and then recalling datepicker after ajax call:
jQuery('.datepicker').datepicker("destroy");
jQuery('#ui-datepicker-div').remove();
I don't know why, but the destroy command does not deletes the ui-datepicker-div and I have to remove it manually! Any clue about this?
回答1:
For dynamically added datpicker
$('body').on('focus',".datepicker", function(){
$(this).datepicker();
});
Demo
回答2:
I broke my head on this problem for a few days and finally I managed to resolve it.
You just need to remove before reinitialize from DOM some div which have been created by jQuery.
It is:
jQuery('#ui-datepicker-div').remove();
jQuery doesn't reinitialize DatePicker if this div is present in DOM.
My working code here:
jQuery(document).ready(function () {
InitDatePickers();
});
function RemoveDatePickers() {
jQuery('#ui-datepicker-div').remove();
}
function InitDatePickers() {
$('#main .date_inp').datepicker($.datepicker.regional["ru"]);
}
function RefreshData() {
RemoveDatePickers();
$.ajax({
type: 'GET',
url: "/",
data: GetFiltersData(),
success: function (data, textStatus) {
$("#main").html(data);
InitDatePickers();
}
});
}
Enjoy, guys!
回答3:
My working solution for this issue is remove class hasDatepicker from element with datepicker after ajax call, then reinitialize datepicker
$("#start").removeClass("hasDatepicker");
jQuery("#start").datepicker({ constrainInput: false, dateFormat: "yy-mm-dd", showButtonPanel: true });
回答4:
Elements added by AJAX have no methods or events bound to them inheritly as they were created AFTER the DOM has loaded. You can work around this with event delegation. However, there's like a better method to what you're trying to do. Instead of adding the datepicker after, why not just have it hidden? If that's not an option, then you need to rebind the datepicker instance in your ajax success.
success: function(data){
$('body').append(//code to create new_ele);
//fire off the datepicker again.
$('new_ele').datepicker();
}
来源:https://stackoverflow.com/questions/27577558/jquery-datepicker-doesnt-work-after-ajax-call-if-its-already-on-page