You shouldn't attempt to reload the entire DOM ready function. Particularly harmful is the n+n nature of events if you did, 2 click events on the same element for example could potentially become 4, then 8 etc. if the DOM ready function is repeatedly re-fired by them.
You can avoid this by taking out the code that you need to run once you're done with your ajax call and presumably the population of the element that you're hoping would benefit from the event you wish to re-initialise.
$(document).ready(function()
{
initialise();
//... Resume with DOM ready
});
function initialise()
{
// create event here that needs re-initialising
}
So when you're done with your ajax call just call initialise()
again.
Alternatively look to using .on
and using it's bubbling up capabilities, this is how I would handle this kind of problem. It avoids you having to ever think about 're-initialising' any part of the DOM ready functions in your scripts.
Additional from comments
.on
allows you to bind events to low level elements on the page that do not change at any time, whilst allowing you to control which of the dynamic elements actually trigger the event within that container.
<div id="container">
<div id="ajax-content">
<a href="#" class="created-link">A new link</a>
</div>
</div>
So we know that the <a>
is created by an ajax function after the DOM ready event is fired, therefore any direct events applied to it then would not work.
Instead we would bind the event to a lower level unchanged element and bubble up to the containing dynamic DOM element.
$('#container').on('click', '.created-link', function(event)
{
event.preventDefault();
// Your normal onclick code
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…