【问题标题】:ReferenceError: $ is not defined jQuery ColorboxReferenceError: $ 未定义 jQuery Colorbox
【发布时间】:2014-03-28 19:19:05
【问题描述】:

几天前我在使用 jQuery colorbox,它工作得非常好,但是在我升级到 jQuery v1.11.0 之后,它突然完全停止工作了。

使用萤火虫检查我发现以下任何错误;

ReferenceError: $ 未定义 $(document).ready(function(){

下面的这段代码现在充当普通的href。

<script src="http://code.jquery.com/jquery-1.11.0.min.js" defer="defer"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js" defer="defer"></script>
<script src="https://raw.github.com/jackmoore/colorbox/master/jquery.colorbox-min.js" type="text/javascript" defer="defer"></script>
<link id="stylesheet" type="text/css" href="js/popup/box/colorbox.css" rel="stylesheet" />

    <script type="text/javascript">
    $(document).ready(function(){
        $("a.popup").colorbox({iframe:true, innerWidth:680, innerHeight:401});
    });
    </script>

<a class="popup" href="/core/ajax/status.php?ID=143" title="Status">View Status</a>

【问题讨论】:

  • 请jsfiddle提供!
  • 放弃使用 defer,正如答案所建议的那样。你也不能从 GitHub 引用 JS 文件,因为它返回一个 text/plain mime 类型。
  • 感谢大家解决了我的问题。

标签: jquery colorbox


【解决方案1】:

这是因为你有defered jQuery 的加载,所以当你的内联脚本块执行时,jQuery 还没有加载。

scriptdefer 属性告诉浏览器处理脚本的加载直到文档被解析

不要延迟加载 jQuery

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="https://raw.github.com/jackmoore/colorbox/master/jquery.colorbox-min.js" type="text/javascript"></script>

另一种选择是通过将脚本移动到单独的 js 文件并将其作为延迟资源包含,从而使您的脚本也以延迟方式执行,例如

<script src="http://code.jquery.com/jquery-1.11.0.min.js" defer="defer"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js" defer="defer"></script>
<script src="https://raw.github.com/jackmoore/colorbox/master/jquery.colorbox-min.js" type="text/javascript" defer="defer"></script>
<script src="test.js" defer="defer"></script>

【讨论】:

    【解决方案2】:

    Defer 告诉浏览器在执行该脚本块中的 javascript 之前等待“直到它准备好”。通常这是在 DOM 完成加载并且 document.readyState == 4 之后。

    所以当 $(document).ready 被调用时 jquery 不会被加载。去掉 defer 属性,一切都会正常工作。

    【讨论】:

      【解决方案3】:

      问题是你的脚本

      <script type="text/javascript">
      $(document).ready(function(){
          $("a.popup").colorbox({iframe:true, innerWidth:680, innerHeight:401});
      });
      </script>
      

      在html解析器看到它之后启动!当页面完成解析时,将执行具有 defer 属性的脚本。

      解决方案:只需从所有脚本中删除 defer 属性!

      【讨论】:

        猜你喜欢
        • 2014-02-25
        • 2020-12-28
        • 1970-01-01
        • 2013-06-29
        • 2012-08-24
        • 2023-03-06
        • 2016-10-27
        • 1970-01-01
        相关资源
        最近更新 更多