Timing issue with jQuery and $(document).ready()
I have the following code block code when the document is ready:
$(document).ready(function() {
createDivs(); // creates some divs with class 'foo';
// iterate
$(".foo").each(function(index) {
alert(index + " - " + $(this).text());
});
}
I find that the "iterate" part misses the divs I created in the createDivs() metho开发者_如何学God entirely! Is there some timing issue I'm not aware of? Why doesn't jquery see the divs that were just created?
In my experience DOM manipulation can act asynchronous at times, possibly due to optimization by the browser, my usual solution is to have createDivs()
return the divs created then use the returned elements aswell
var divs = createDivs();
$('.foo').and(divs).each(function(){
//happy fun time
})
I've found that Javascript is like a bull in an F1 racer when it comes to executing code. There's no making it wait to execute code in any particular chain.
You should probably create a situation where createDivs() is able to fire any dependent code after it is complete vis-a-vis a callback. Without seeing the createDivs code, it's tough to give you a way to implement it.
UPDATE
Really only applies if you're doing an asynchronous call (according to my friends below).
The timing is not the issue. Maybe createDivs()
doesn't add the elements to the DOM?
精彩评论