我正在构建一个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() {
// ...
}