我正在构建一个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