jQuery.getScript() 加载函数失败
jQuery.getScript() fails to load function
我正在尝试加载具有以下功能的脚本:
$.getScript('/js/mymy.js').done(function(){
if(readCookie('my_cookie', 'yes')){
/* do sth here */
}
});
或
$.getScript('/js/mymy.js',function(){
if(readCookie('my_cookie', 'yes')){
/* do sth here */
}
});
其中 "readCookie" 在 mymy.js 中定义,但我收到错误 "readCookie" 未定义...
这里 1 & 2 是我得到帮助的地方,但它不起作用...有什么想法吗?
我确实使用 jQuery 1.8.0
mymy.js 确实包含函数:
jQuery(document).ready(function() {
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
/** There is sth much more here **/
...
/** There is sth much more here **/
});
来自the docs:
The callback is fired once the script has been loaded but not necessarily executed.
换句话说,您不能依赖 success
函数在加载的脚本 执行 后显式调用,例如,它的函数放在全局范围内.
在您编辑之后(IMO 应该是您首先发布的内容)您实际上有 两个 个问题;如所写,它的作用域为 only 在 JQ 的 DOM-ready 函数中。)
readCookie
未定义,因为 readCookie
不是全局的;它仅在 mymy.js
.
中的 document.ready
函数范围内可见
通过删除 document.ready
包装器使函数成为全局函数。
我正在尝试加载具有以下功能的脚本:
$.getScript('/js/mymy.js').done(function(){
if(readCookie('my_cookie', 'yes')){
/* do sth here */
}
});
或
$.getScript('/js/mymy.js',function(){
if(readCookie('my_cookie', 'yes')){
/* do sth here */
}
});
其中 "readCookie" 在 mymy.js 中定义,但我收到错误 "readCookie" 未定义...
这里 1 & 2 是我得到帮助的地方,但它不起作用...有什么想法吗?
我确实使用 jQuery 1.8.0
mymy.js 确实包含函数:
jQuery(document).ready(function() {
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
/** There is sth much more here **/
...
/** There is sth much more here **/
});
来自the docs:
The callback is fired once the script has been loaded but not necessarily executed.
换句话说,您不能依赖 success
函数在加载的脚本 执行 后显式调用,例如,它的函数放在全局范围内.
在您编辑之后(IMO 应该是您首先发布的内容)您实际上有 两个 个问题;如所写,它的作用域为 only 在 JQ 的 DOM-ready 函数中。)
readCookie
未定义,因为 readCookie
不是全局的;它仅在 mymy.js
.
document.ready
函数范围内可见
通过删除 document.ready
包装器使函数成为全局函数。