我正在構建一個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);
雖然這個結果在正確的行爲我不明白。
這導致我的問題:爲什麼我的第一種方法失敗?第二種方法在做什麼?
我認爲django框架使用美元'''符號來代替其他東西,而不是jQuery。因此,您需要在您的jQuery函數中創建一個容器,將jQuery分配給僅用於容器內代碼的美元符號 – Mivaweb 2014-12-02 07:47:47