0

在我的 html 文件中,我正在加载两个执行一些 dom 操作的外部 javascript 文件,第一个只是在 html 中准备页面(注入一些 div 和内容)。第二个定位那些刚刚注入的 div,然后尝试用它做一些事情。

var app = {
    init: function () {
        // event handler goes here
        app.alertMe('Hello');
        app.loadContent();
        app.insertDiv();
    },
    loadContent: function() {
        $('#div1').load('../html/demo_test.html');
    },
    insertDiv: function() {
        $('#div2').append('<strong>YEEEEEEAP</strong>');
    },
    alertMe: function(a) {
        alert(a);
    }

};

$(function () {
    app.init();
})

第二个是这个引导库。我的html文件如下

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>A</title>
            <script type="text/javascript" src="page_prep.js">
    </script>
    </head>
    <body>
        body
    </body>
    <script type="text/javascript" src="bootstap_lib.js">
</html>

尽管我的加载顺序正确,但库似乎在我的 custom.js 之前加载,这最终导致操作不起作用,因为找不到需要存在的 div。仔细调试已证明 div 是在之后被注入的。

有什么理由可能会出现这种情况?

4

1 回答 1

1

您正在推迟注入,直到页面完成加载,引导脚本在浏览器下载后立即运行。

将您的脚本文件移动到您的引导脚本上方,然后更改:

$(function () { //This defers execution
    app.init();
})

对此:

app.init(); //This executes immediately
于 2013-08-15T20:06:06.633 回答