问题
I've got an accordion in the container:
<div id="address_results"></div>
Now I fill in the html (an accordion) via an ajax call. It works fine but only by the first ajax call. By the second, third, etc. call, the animation of the accordion doesn't work.
// Ajax request
$(this).submit(function() {
var postal = $(o.postalDiv).val();
$.getJSON(o.url,{ action: o.action, id: o.id, postal: postal } , function(json) {
var result = json.content;
var addresses = result['addresses'];
var strXML = result['xml'];
outputHtml(addresses);
});
return false;
});
// Ajax request success
function outputHtml(addresses) {
$(o.resultsDiv).html(addresses);
// Generate the accordion
$(o.resultsDiv).accordion({
autoHeight: false,
header:'div.toggler',
active: false,
collapsible: true
});
When I remove/append the div
before I fill in the accordion:
$('#addresses_results').remove();
$('#reswrapper').append('<div id="address_results"></div>');
then it works fine. But this can be the right way?
(sorry my English, is not my native language) thanks!
回答1:
Try :
$('#addresses_results').accordion('destroy').accordion();
回答2:
The following line doesn't work, because by the first ajax call the accordion isn't exists.
$('#addresses_results').accordion('destroy').accordion();
The solution is to check if the accordion already exists:
if ($(o.resultsDiv).hasClass('ui-accordion')) {
$(o.resultsDiv).accordion('destroy');
}
The whole Solution:
(function ($) {
$.fn.address = function (options) {
var defaults = {
url: '/ajax.php',
action: 'fmd',
id: 0,
resultsDiv: '#address_results',
postalDiv: '#address_postal'
};
var o = $.extend(defaults,options);
// Ajax request
$(this).submit(function() {
var postal = $(o.postalDiv).val();
$.getJSON(o.url,{ action: o.action, id: o.id, postal: postal } , function(json) {
var result = json.content;
var addresses = result['addresses'];
var strXML = result['xml'];
outputHtml(addresses);
});
return false;
});
// Ajax request success
function outputHtml(addresses) {
$(o.resultsDiv).html(addresses);
// Check if the accordion already exist. if so destroy it
if ($(o.resultsDiv).hasClass('ui-accordion')) {
$(o.resultsDiv).accordion('destroy');
}
// Generate the accordion
$(o.resultsDiv).accordion({
autoHeight: false,
header:'div.toggler',
active: false,
collapsible: true
});
}
};
})(jQuery);
Thanks!
来源:https://stackoverflow.com/questions/14581713/jquery-accordion-loading-via-ajax