【发布时间】:2023-07-07 19:30:01
【问题描述】:
我正在构建一个 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);
虽然这会导致正确的行为我不明白。
这引出了我的问题:为什么我的第一种方法失败了?第二种方法是做什么的?
【问题讨论】:
-
我认为 django 框架使用美元
$符号代替 jQuery。因此,您需要围绕 jQuery 函数创建一个容器,在其中将 jQuery 分配给美元符号,仅用于容器内的代码
标签: javascript jquery html django events