$使用jQuery和Google Code Repository未定义错误
我正在尝试从jQuery网站复制标签演示。 我正在使用的示例页面是:http: //yazminmedia.com/playground/jquerytabs.html
我想使用Google Code Repository来利用缓存。 我在页面的头部有以下代码:
google.load("jquery", "1"); google.load("jqueryui", "1"); $(function() { $("#tabs").tabs(); });
但是,我不断收到以下错误 – “$ is not defined”代表以下行:
$(function() {
有没有人知道可能会导致错误的原因是什么?
谢谢!
google.load
在其自身之后注入一个脚本元素。 因此,脚本标记的显示顺序为:
// google loads first // ask "google" to load jQuery and jQuery UI // But, jQuery gets included here (after its usage) // and jQuery UI gets included here
由于在jQuery包含在文档顺序之前出现$
的使用,因此不会在第二步中定义$
。
解决方案是拆分脚本标记,以便google.load
语句出现在自己的脚本标记中。 因此,如果您用以下代码替换代码:
现在,文档中脚本标记的顺序为:
// first google loads // then we ask "google" to load jQuery and jQuery UI // jQuery loads // jQuery UI loads // now our script can run smoothly
请注意,包含jQuery代码的脚本元素现在出现在jQuery之后,因此您的代码应该可以工作,并且应该从那里定义$
或jQuery
。
但是,更好的解决方案是使用google
的直接链接,或使用回调,而不是依赖google
的加载顺序的行为。
或者,使用onLoad回调:
google.load("jquery", "1"); google.load("jqueryui", "1"); google.setOnLoadCallback(function() { // jQuery should be define here $(function() { alert($("h1").text()); }); });
出于某种原因,我得到了同样的错误
我通过将此脚本添加到每个页面来逃避它
然后使用
$j("#tabs").tabs();