使用 jquery 在 django 文档准备就绪时运行代码

Using jquery to run code when django document is ready

本文关键字:运行 代码 准备就绪 文档 jquery django 使用      更新时间:2023-09-26

我正在构建一个django管理站点,并使用javascript和jquery(2.0.3)为表单添加一些额外的功能。

我正在将脚本导入我的页面,如下所示:

<html>
    <head>
        <script type="text/javascript" src="/static/admin/js/jquery.js"></script>
        <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
        <script type="text/javascript" src="/static/project/js/project.js"></script>
    </head>
    <!-- ... -->
</html>

起初,我将以下代码放在project.js末尾:

function tryCustomiseForm() {
    // ...
}
$(document).ready(tryCustomiseForm); 

不幸的是,这会导致最后一行出现Uncaught TypeError: undefined is not a function异常。

然后我尝试了ready()的替代语法,但没有更多的运气。

最后,我探索了change_form.html模板并找到了这个内联javascript:

<script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            $('form#{{ opts.model_name }}_form :input:visible:enabled:first').focus()
        });
    })(django.jQuery);
</script>

能够修改它以满足我的需求,现在我的project.js以:

(function($) {
    $(document).ready(function() {
        tryCustomiseForm();
    });
})(django.jQuery);

虽然这会导致正确的行为,但我不明白

这就引出了我的问题:为什么我的第一个方法失败了?第二种方法在做什么?

很难从你发布的代码中分辨出来,但看起来$变量没有在你的模板中分配给jQuery;因此$()结构抛出了undefined function错误。

后者起作用的原因是因为它在你的 DOMReady 处理程序周围放置了一个闭包,它传入django.jQuery ,我假设它是模板中noConflict jQuery 赋值变量,并将其分配给该范围内的$

(function($) { // < start of closure
    // within this block, $ = django.jQuery
    $(document).ready(function() {
        tryCustomiseForm();
    });
})(django.jQuery); // passes django.jQuery as parameter to closure block

Django 文档对此进行了解释:jQuery 是命名空间的,因此您可以使用 django.jQuery 在管理模板中引用它。

试试

$(document).ready(function(){
 tryCustomiseForm();
}); 
function tryCustomiseForm() {
    // ...
}