简体   繁体   English

jquery $document.ready 是否等待 json 文件被加载?

[英]Does jquery $document.ready wait for json files to be loaded?

I get HTML configuration data from a json file.我从 json 文件中获得 HTML 配置数据。 When that has loaded, I need to make sure that the document is ready before plugging the HTML into existing elements.加载后,在将 HTML 插入现有元素之前,我需要确保文档已准备就绪。

    var cfg;
    function getJSONconfigdata() {
        $.getJSON("/quizdata.json", function (json) {
            cfg = json;          
            //Now do everything else
            init();
        });
    }
    getJSONconfigdata()

    function init(){
        //Plug cfg values into existing dom elements. but they may not exist yet.
        //...
    }

init() is called after the json file has been parsed, but how do I make sure the dom is also ready? init() 在 json 文件被解析后被调用,但我如何确保 dom 也准备好了? I have tried $(function (){ init(); });我试过 $(function (){ init(); }); but cant make it work - it seems to fire before json is loaded.但不能让它工作 - 它似乎在 json 加载之前触发。

Yes, the $(document).ready() runs when the DOM is prepared for JS.是的, $(document).ready()在 DOM 为 JS 准备好时运行。 When many people use jQuery they will put all of their code that will interact with page elements within the $(document).ready() statement to ensure that.当许多人使用 jQuery 时,他们会将与页面元素交互的所有代码放在$(document).ready()语句中以确保这一点。 So所以

$( document ).ready(function() {
    var cfg;
    function getJSONconfigdata() {
        $.getJSON("/quizdata.json", function (json) {
            cfg = json;          
            //Now do everything else
            init();
        });
    }
    getJSONconfigdata()
});

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

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