2014-12-02 195 views
3

我正在構建一個django管理站點,並且正在使用javascript和jquery(2.0.3)向窗體添加一些額外的功能。使用jquery在django文檔準備就緒時運行代碼

我進口腳本到我的網頁是這樣的:

<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); 

雖然這個結果在正確的行爲我不明白

這導致我的問題:爲什麼我的第一種方法失敗?第二種方法在做什麼?

+1

我認爲django框架使用美元'''符號來代替其他東西,而不是jQuery。因此,您需要在您的jQuery函數中創建一個容器,將jQuery分配給僅用於容器內代碼的美元符號 – Mivaweb 2014-12-02 07:47:47

回答

2

很難從你發佈的代碼告訴,但它看起來像$變量在你的模板沒有分配給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 
+0

看起來這是正確的,因爲以下工作是正確的:django.jQuery(document).ready(tryCustomiseForm) ;'謝謝你的幫助。 – 2014-12-02 07:59:22

+0

@KellyThomas沒問題,很高興幫助 – 2014-12-02 08:00:47

+1

@KellyThomas,我發現[jQuery noconflict docs](http://api.jquery.com/jquery.noconflict/)對解釋這個很有幫助。 – rnevius 2014-12-02 08:18:24

-1

嘗試

$(document).ready(function(){ 

tryCustomiseForm(); 

}); 

function tryCustomiseForm() { 
    // ... 
} 
+0

這在邏輯上與OP第一次嘗試的完全相同,但沒有奏效。 – 2014-12-02 07:49:28

+0

這與'tryCustomiseForm()'函數在另一個匿名函數中調用的函數不完全相同。 – 2014-12-02 08:16:43

+0

@SebastianZartner語義。 – 2014-12-03 07:41:51

1

Django文檔explain this:jQuery是命名空間,所以你可以使用django.jQuery指IT管理員TEM內鍍。

相關問題