【问题标题】:"Uncaught ReferenceError: $ is not defined" error on Google Chrome (but works on Firefox and Safari)Google Chrome 上的“Uncaught ReferenceError: $ is not defined”错误(但适用于 Firefox 和 Safari)
【发布时间】:2013-03-10 22:46:12
【问题描述】:

我正在尝试让这个 SO 问题中的示例代码在我的系统上运行

getting the X/Y coordinates of a mouse click on an image with jQuery

它显示鼠标在div 内的点击位置。它在FirefoxSafari 上运行良好,但在Chrome 上没有更新,我想知道我是否做错了什么。 我使用的是 Google Chrome 版本 23.0.1271.101

这是我正在使用的代码。

<html>

<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>

<body>
<p>Click to see the position!</p>
<div class="box" style="width: 200px; height: 200px; background: #F00">&nbsp;</div>
<p id="position">Position will go here</p>
<script>
$(document).ready(function() {
    $('.box').click(function(e) {
        var offset = $(this).offset();
        $('#position').html(Math.round(e.clientX - offset.left) + ", " + Math.round(e.clientY - offset.top));
    });
});
</script>

</body>
</html>

更新: 这是我在 Chrome 的 JavaScript 控制台 Uncaught ReferenceError: $ is not defined 上看到的错误,但我不知道该怎么做。

更新2:

我在打开 JavaScript 控制台的同时清除了浏览器缓存并重新加载了页面,并注意到一个我以前从未见过的错误

[blocked] The page at https://<mywebsite>/index.html ran insecure content from http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js.
Uncaught ReferenceError: $ is not defined 

所以,我下载了jquery.min.js,并把它和index.html放在同一目录下,并将脚本的加载改为

<script src="./jquery.min.js" type="text/javascript"></script>

它现在可以在所有三种浏览器上运行......所以出于某种原因,Chrome 是唯一一个抱怨 jquery.min.js 的 url 不安全的浏览器。使问题更加复杂的是,当我进入 JavaScript 控制台时,它并没有给我那个错误,直到我清除了缓存 并且我打开了 JavaScript 控制台,我才看到它。

【问题讨论】:

    标签: javascript jquery google-chrome firefox safari


    【解决方案1】:

    您得到的错误是执行脚本时未加载 jQuery。因此,当您尝试使用 $ 时,没有定义它。

    另外,您的屏幕截图显示的标记与您的示例不同。

    【讨论】:

    • 是的,我做了一些更改,试图在发布标记后和截屏之前解决问题......很好的观察......这些更改(将脚本移动到头部)没有做出不同。
    • +1 观察到$ is not defined when you try to use it,这实际上是问题所在,但根本原因是由于某些安全相关原因(我不明白)它没有下载 jQuery。
    • @amdn 您看到的错误是因为您尝试从不安全的 HTTP 协议加载并注入安全 HTTPS 协议的页面而生成的。如果你从脚本标签中删除协议,浏览器应该不会再抱怨了。
    • @Ragnarokkr 我认为你是对的,但是,如果我从 url 中删除 HTTPS,它无论如何都会插入到所有三个浏览器中,但是 Chrome 是唯一一个抱怨 jquery 的 url 不安全的.
    • @Cyrus 如果您删除建议 Move your script tag to the end of the body tag - 它没有解决问题 - 我会选择您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2020-04-08
    • 1970-01-01
    • 2021-06-03
    • 2015-12-24
    • 1970-01-01
    相关资源
    最近更新 更多