如何使这个jQuery函数遵循“document.ready”?

3
如何让下面的jQuery函数在DOM加载完成后再读取?我以为在函数声明的开头指定"$(document).ready(function..."就可以解决问题,但当我的页面执行时,该函数不起作用,我可以在浏览器的开发者控制台中看到消息"Uncaught ReferenceError: $ is not defined"。
这是我的基本模板:
# 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调用放在页面末尾有一些很好的性能原因。
3个回答

1
基本上,问题在于使用jQuery方法之前需要先引入jQuery。通常你需要将jQuery放在其他代码之前。
<script src="https://code.jquery.com/..."></script>
<script src="js/bootstrap.min.js"></script>

在html的<head>标签中
我对Django不太熟悉,但是你不想把jQuery和bootstrap放在文档头部有什么原因吗?
无论如何,你需要在你的代码之前包含那些脚本。
否则,你可以参考这个:$(document).ready equivalent without jQuery

1
通常最佳实践是将js脚本放在底部,因为它会锁定页面加载。但是当涉及到jQuery时,最好将其放在样式之后,其余的脚本可以放在底部。
要解决您的问题,您只需要在使用$变量之前移动jQuery导入。这会导致错误,因为此时$还不存在。
# base.html
<!DOCTYPE html>
<html>
...
<script src="https://code.jquery.com/..."></script>    <!-- move this line here -->
</head>
<body>
{% block page_container %} {% endblock %}
...
<script src="js/bootstrap.min.js"></script>
...
</body>
</html>

0

由于您正在使用$(document).ready函数,实际上您正在尝试访问未加载的jquery变量$

因此,一种解决方案是在头部加载jquery,其余的javascript文件可以驻留在页面底部,所有JS代码都可以在.ready事件中添加。

但是,如果您想将jQuery嵌入页脚,则可以使用多种方法来实现,如下面问题的答案所展示:

纯JavaScript等效于jQuery的$.ready(),如何在页面/ dom准备好时调用函数

我喜欢的一种方法:

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here

})();
</script>

建议:

但是我建议至少在头部使用jQuery和页面中的其他组件,然后可以在页面末尾加载其余的JS文件。由于jQuery是页面的非常重要的组件,其他内部/外部组件可能会依赖它。其余的则取决于您的用例和实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接