2

我正在为在 html 文档末尾嵌入 jQuery 的 cms 编写插件。

我确实在我的模板代码中动态定义了一些变量,如下所示:

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

这段代码是我插件的一部分,它没有嵌入到每个页面上。因此,名称不是在每个页面上都定义的。

我也确实在一个单独的文件中有这个 Javascript 代码(由 cms 自动添加到页面末尾):

var MyNamespace = (function() {

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

    return {
        MyClass: MyClass
    }

})();

如果 jQuery 嵌入在顶部,我会在我的模板代码中做这样的事情:

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

    $(document).ready(function() {
        new MyNamespace.MyClass(name);        
    });
</script>

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

我能做些什么?好的旧 document.ready 是明智的做法吗?

4

2 回答 2

5

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

如果你在你的页面做这样的事情

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

    function runWhenReady(){
        new MyNamespace.MyClass(name);        
    }
</script>

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

$('document').ready(function() {
    if (typeof runWhenReady != 'undefined') {
        runWhenReady();
    }
});

如果您有创意,您可以将“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>
于 2012-04-27T14:17:24.533 回答
0

编辑 - 好的,你不应该弄乱全局空间,我不明白你为什么不把你<script>的标签放在你包含 jQuery 的标签下面。否则你可以进行 AJAX 调用

<script>


    $('document').ready(function() {
        $.getJSON('getmyname.php', function(data){
            new MyNamespace.MyClass(data.name);        
        });
    });
</script>
于 2012-04-27T14:02:32.737 回答