简体   繁体   English

jQuery和$(document).ready()的计时问题

[英]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() method entirely! 我发现“ iterate”部分完全错过了我在createDivs()方法中创建的div! Is there some timing issue I'm not aware of? 有一些我不知道的计时问题吗? Why doesn't jquery see the divs that were just created? 为什么jquery看不到刚创建的div?

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 以我的经验,DOM操作有时可能异步执行,这可能是由于浏览器的优化所致,我通常的解决方案是让createDivs()返回创建的div,然后也使用返回的元素

var divs = createDivs();
$('.foo').and(divs).each(function(){
    //happy fun time
})

The timing is not the issue. 时间不是问题。 Maybe createDivs() doesn't add the elements to the DOM? 也许createDivs()不会将元素添加到DOM中?

I've found that Javascript is like a bull in an F1 racer when it comes to executing code. 我发现Java在执行代码时就像是F1赛车手的牛。 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. 您可能应该创建一种情况,其中createDivs()能够在完成回调后触发所有依赖代码。 Without seeing the createDivs code, it's tough to give you a way to implement it. 没有看到createDivs代码,很难为您提供实现它的方法。

UPDATE 更新

Really only applies if you're doing an asynchronous call (according to my friends below). 仅在您进行异步调用时才适用(根据下面的朋友所述)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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