问题
I have a jquery datepicker inside a div that is updated via ajax. I'm able to open datepicker once after whole page reloads, but after ajax updates only a div that includes datepicker input, I'm not able to see datepicker. I have tried a solutions that I wound for similar problems, with no luck.
I'm not very familiar with jquery and ajax, so maybe someone can see the problem immediatly.
I have a jquery function that includes ajax:
function example(){
$.ajax({
url: "page.php",
cache: false,
success: function(data){
$('#div').html(data);
}
});
}
Ajax reloads a div, which has a datepicker input inside, which looks like this :
<input type="text" id="datepicker"/>
Datepicker is constructed this way:
$(function() {
$("#datepicker").datepicker({dateFormat: "dd.mm.yy"});
$.datepicker.setDefaults(
$.extend(
{'dateFormat':'yy-mm-dd'},
$.datepicker.regional['fi']
)
);
});
What do I have to do, to be able to see datepicker every time div updates via ajax? Some suggested datepicker to be refresh at ajax success, I didnt get it working this way, or didnt know how!
回答1:
One way to do it would be to rerun the .datepicker() initializer on ajax success.
Change the datepicker code to:
function applyDatepicker(elem) {
$(elem).datepicker({dateFormat: "dd.mm.yy"});
//... Your datepicker code
}
Then once on document ready:
$(document).ready(function(){
applyDatepicker('#datepicker');
})
And once in your ajax success callback:
$.ajax({
//... other ajax params,
success: function(){
//... success callback code
applyDatepicker('#datepicker');
}
});
Also, as @adrenalin suggests, the only way to figure the best practice would be to know more about your code.
A suggestion would be to change the element to have a class="datepicker" rather than an id for the main reason that there could be multiple datepickers in a page and id's are always meant to be unique. As a beginner, I suggest the easiest approach is to try to imagine an ID as an element's Proper Noun whereas Class will be it's Common Noun or Adjective!
回答2:
The datepicker would need to be initialized as the one you loaded with AJAX is completely new element and was not there when you initialized it in the first place. None of the original events are bound to the new element anymore. Do it on the AJAX load success callback (which depends on the way you are doing it.
It really depends on how the code is constructed to tell what the best practise would be, but if you load the content in general in one place only, either repeat the datepicker initialization or wrap it in a function and call it wherever it is needed.
来源:https://stackoverflow.com/questions/17965561/datepicker-wont-start-after-ajax-div-reload