簡體   English   中英

在django文檔准備就緒時使用jquery運行代碼

[英]Using jquery to run code when django document is ready

我正在構建一個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最后一行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);

雖然這導致了正確的行為,但我不明白

這引出了我的問題:為什么我的第一種方法失敗了? 第二種方法是做什么的?

從你發布的代碼中很難說出來,但看起來你的模板中的$ variable沒有分配給$ variable; 因此$()構造拋出了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() {
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM