我正在使用 jQuery。这是我在主页上的编码:
<script type="text/javascript" src="script.js">
</script>
我的 script.js 是:
$(document).ready(function(){
$("#title").click(function () {
alert("Works!");
});
});
我的完整代码可以在这里找到:http://pastie.org/8676656 .
使用浏览器上的一个工具,我发现我的 javascript 代码有一个错误:
ReferenceError: Can't find variable: $
在线:
$(document).ready(function() {
如有任何帮助,我们将不胜感激。
最佳答案
在使用之前必须导入 jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
注意它正在使用 //
作为协议(protocol)(不是 http://
或 https://
),这意味着:如果您的 .html 文件位于 http://
服务器,它将从 http://ajax.google...
获取 jQuery , 如果它位于 https://
服务器,它将从 https://ajax.google...
获取它.
注意:如果在开发过程中,您在浏览器而不是服务器中打开 HTML 文件,您应该指定协议(protocol),如 this answer ,否则将无法工作:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
此外,如果可能,您应该将 .js 文件放在页面底部,就在关闭之前 </body>
.查看更多 here .
关于javascript - ReferenceError:找不到变量:$,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21417836/