我正在构建一个 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
关于javascript - 当 django 文档准备好时使用 jquery 运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27244227/