问题
I've got the accordion working fine on pageload, however upon user interaction with some elements on the page, I am using ajax to rebuild the HTML of the accordion. Then, I try to re-initialize the accordion again with
$('#accordion').accordion({
active: false,
autoHeight: false,
clearStyle: true,
collapsible: true,
header: 'h3'
});
but... it doesn't seem to be taking.
The new block of rendered HTML isn't applying the accordion rules. Instead it just stays open as a large list.
I've even tried setTimeout() for re-calling the accordion just incase it was trying to initialize before the rendered HTML is returned in the callback.
The HTML that is rendered in the callback is the exact same as that of the pageload (with exception to the DOM additions that occur when the Accordion method is effective)
回答1:
Destroy the accordian before repopulating it with data.
$('#accordion').accordion('destroy');
回答2:
For me the following works perfectly and the code is very clear - initiate the accordion div on pageload using:
$('#accordion').accordion()
Then on any change I call:
$('#accordion').accordion( "refresh" )
From the Docs :
Process any headers and panels that were added or removed directly in the DOM and recompute the height of the accordion panels. Results depend on the content and the heightStyle option.
This works for all situations: it means you can use it after you've added/removed/unchanged/recreated your content and the "accordion" element will readjust itself.
You should avoid destroying and creating everything on each change, it doesn't make sense and performance could deteriorate as you scale up.
来源:https://stackoverflow.com/questions/1301783/re-initialize-jquery-accordion-on-callback