【发布时间】:2016-10-15 14:00:12
【问题描述】:
如何让下面显示的 jQuery 函数等到 DOM 加载完毕后再读取?我认为在函数声明的开头指定“$(document).ready(function...”可以解决问题,但是当我的页面执行时,该函数不起作用,我可以看到消息“Uncaught ReferenceError: $ 未定义”在我的浏览器的开发者控制台中。
这是我的基本模板:
# base.html
<!DOCTYPE html>
<html>
...
<body>
{% block page_container %} {% endblock %}
...
<script src="https://code.jquery.com/..."></script>
<script src="js/bootstrap.min.js"></script>
...
</body>
</html>
这个 Django 模板扩展(被包围)基本模板:
# upload_file.html
{% extends base.html %}
(HTML for form ...)
<label class="btn btn-success btn-file">
Select Photo <input type="file" name="photo" style="display: none;">
</label>
(more HTML...)
<script>
$(document).ready(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
});
</script>
当然,如果我将调用 jQuery 的脚本标签向上移动到我的基本模板中的块内,函数就会执行。但是,我更愿意将 jQuery 脚本元素保留在基本模板的底部,如 Bootstrap 文档中所示。如果在我的页面中调用它的函数之后引用了 jQuery,有没有办法让这个函数工作?
谢谢。
-- 跟进--
我将答案归功于 fyrb,因为他首先回答了我,我最终按照他的建议做了,但我也很欣赏其他答案。为了其他有这个问题的人的利益,我在下面添加了一些关于这个主题的好帖子的链接。将 jquery 调用放在页面末尾有一些良好的性能原因,这些文章将在这些文章中看到。
- Stop paying your jQuery tax
- Should Jquery code go in header or footer?
- When do you choose to load your javascript at the bottom of the page instead of the top?
- why javascript runs when at bottom of page or sometimes from top of page
- pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
- $(document).ready equivalent without jQuery
【问题讨论】:
标签: jquery django twitter-bootstrap