如何在页脚中插入jQuery时定义变量

shr*_*ing 2 javascript jquery footer

我正在为一个在html文档末尾嵌入了jQuery的cms编写插件.

我在我的模板代码中动态定义了一些变量:

<script>
    var name = '<?php echo $nameTakenFromTheDatabase; ?>';
</script>
Run Code Online (Sandbox Code Playgroud)

此代码是我的插件的一部分,并未嵌入到每个页面中.因此,并未在每个页面上定义名称.

我也有一个单独的文件中的这个Javascript代码(由cms自动添加到页面结束):

var MyNamespace = (function() {

    MyClass = function(name) {
        // Do something with name
    }

    return {
        MyClass: MyClass
    }

})();
Run Code Online (Sandbox Code Playgroud)

如果jQuery嵌入在顶部,我会在我的模板代码中执行以下操作:

<script>
    var name = '<?php echo $nameTakenFromTheDatabase; ?>';

    $(document).ready(function() {
        new MyNamespace.MyClass(name);        
    });
</script>
Run Code Online (Sandbox Code Playgroud)

但是,由于jQuery包含在底部,我无法做到($尚未定义).我也不能只是将jQuery-DomReady调用添加到单独的代码文件中,因为这是在每个页面上执行的,但名称 var不会在每个页面上都被初始化并且会破坏代码.

我能做什么?好的旧文件.已经是明智的做法吗?

aab*_*erg 5

您可以在脚本中定义方法,并从全局javascript文件中执行它们.

如果您在页面中执行此类操作

<script>
    var name = '<?php echo $nameTakenFromTheDatabase; ?>';

    function runWhenReady(){
        new MyNamespace.MyClass(name);        
    }
</script>
Run Code Online (Sandbox Code Playgroud)

然后在页面底部添加的全局文件中,您可以执行以下操作:

$('document').ready(function() {
    if (typeof runWhenReady != 'undefined') {
        runWhenReady();
    }
});
Run Code Online (Sandbox Code Playgroud)

如果你很有创意,可以让'runWhenReady'成为一个方法集合,当页面准备就绪时,它们总会被加载.

编辑我添加了一个使用数组的示例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>

    <script type="text/javascript">
        // check if array is already created. This is necessary if it is possible to render multiple pages which uses the runWhenReadyFunctions collection.
        if (typeof runWhenReadyFunctions == 'undefined'){
            window.runWhenReadyFunctions = new Array();
        }

        runWhenReadyFunctions.push(function(){
            $('#testDiv').text('hello world!');
        });

        runWhenReadyFunctions.push(function(){
            $('#testDiv2').text('hello another world!');
        })

    </script>


    <div id="testDiv"></div>
    <div id="testDiv2"></div>

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        if (typeof runWhenReadyFunctions != 'undefined') {
            $.each(runWhenReadyFunctions, function(idx, func){
                func();
            });
        }
    </script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)