简体   繁体   中英

jQuery document.ready() not firing for dynamically loaded content

I've got a PHP file (called aboutMe.php) that contains some HTML as follows:

 <script type="text/javascript" src="/aboutMe.js"></script> <div id="aboutme-gender" class="aboutme-block"> <div class="aboutme-question">My gender is:</div> <div class="aboutme-error">Please select your gender.</div> <div class="aboutme-answer"> <input id="gender-male" name="the-gender" type="radio" value="1" /> <label for="gender-male">Male</label> <input id="gender-female" name="the-gender" type="radio" value="2" /> <label for="gender-female">Female</label> </div> </div> 

The aboutme.js file contains a function as follows:

jQuery(document).ready(function($) {.....does stuff to the tags in the HTML});

This all works fine if the page is loaded directly. However when another page wants to load this dynamically as follows:

$("#load-aboutme-here").load("aboutMe.php");

...the document.ready() event doesn't fire and things don't get tagged.

I've seen similar posts but can't quite get what I need from them. Have done things like substitute the document.ready() for window.load() but then it doesn't even work at all when the aboutMe.php page is loaded directly.

Any ideas much appreciated - this is driving me nuts although I suspect it's an easy fix!

Thanks Iain

If I understood your problem correctly, I believe you could just create a callback for the .load() function like so:

$("#load-aboutme-here").load("aboutMe.php", null, function()
{
    // Code to be executed when aboutMe.php is loaded.
    // i.e. The code in aboutMe.js
});

Note that the document is the main page...not subsequent files you retrieve

The document was ready long before the ajax is done so any $(document).ready() that is called after it is ready will fire immediately. In your case it will fire before the elements exist

Move the script tag below the html that the code is referencing

<div id="aboutme-gender" class="aboutme-block">
   .......
</div>
<script type="text/javascript" src="/aboutMe.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM