The scenario is as follows.
On a Parent Page we have a div tag with id and Name "placeHolder".
- Step 1: "placeHolder" is filled with Page1 content through an ajax call.
- Step 2: "placeHolder" is filled with Page2 content through an ajax call.
- Step 3: "placeHolder" is again filled with Page1 content through an ajax call.
When the pages are loaded for the first time $(document).ready(fun开发者_JAVA百科ction() is getting called , but from step 3 onwards, the ready function is not getting called.
Any direction would be appreciated.
I think you're implying that the elements that get injected into the div via your ajax call are losing their event handlers. If that is the case, you will need to delegate those events using live
or rebind them to your elements within your ajax method's success
callback. A $(document).ready()
block will only execute the first time the page is loaded.
Say for instance, one of the elements that gets replaced through your ajax call is an anchor with class="something"
:
$('a.something').live("click", function() {
alert('hello');
});
The above will ensure that when the anchor gets replaced via an ajax call, the click handler will still execute.
you should use complete
callback in your ajax call
$(document).ready(...)
is only called when the document loads: if you are loading content via Ajax then this event will only fire once the first time the page loads. So you would be best doing as karim79 suggests and using live or your Ajax method's success callback.
My understanding is that $(document).ready) is only called when the browser completes it's initial GET of a webpage.
If you want to trigger a function then you can use the success callback in your Ajax call.
"When the pages are loaded for the first time $(document).ready(function() is getting called , but from step 3 onwards, the ready function is not getting called" - making the assumption that 1-3 are executed in sequence on initial page load. So, YES - that is a valid description of how it works.
The $(document).ready() is an EVENT HANDLER - in other words: Document is ready to be accessed and scripts have completed loading. Other events occur after that (and before, but for this purpose, jQuery is "ready" when ready.
Just an FYI the following is also valid:
function myOnLoaded()
{
// do my load thing here
}
$(document).ready(myOnLoaded);
This calls myOnLoaded when the event (the ready) fires.
The answers above about the reason why $(document).ready is not working are correct.
But $(document).live has been deprecated in jquery 1.9 http://jquery.com/upgrade-guide/1.9/#live-removed
In stead, you should be using $(document).on Documentation here: http://api.jquery.com/on/
function myOnLoaded()
{
// do my load thing here
}
$(document).on("click", "a.something", myOnLoaded)
精彩评论