jQuery.getScript()无法加载函数 [英] jQuery.getScript() fails to load function

查看:567
本文介绍了jQuery.getScript()无法加载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $。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

a& 2 是我得到帮助如何做的地方,但它不工作...任何想法?

我使用jQuery 1.8.0



mymy.js包含一个函数:

$ p $ 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;
}

/ **这里有更多** /
...
/ **这里有更多** /
});


解决方案

readCookie 未定义,因为 readCookie 不是全局的;它仅在 mymy.js 中的 document.ready 函数范围内可见。



通过移除 document.ready 包装来制作全局函数。


I am trying to load a script with a function like:

$.getScript('/js/mymy.js').done(function(){ 
    if(readCookie('my_cookie', 'yes')){
        /* do sth here */
    }
});

or

$.getScript('/js/mymy.js',function(){   
    if(readCookie('my_cookie', 'yes')){
        /* do sth here */
    }
});

where "readCookie" is defined in mymy.js but i get an error "readCookie" is not defined...

Here 1 & 2 is where i have got help how to do, but it does not work... Any Ideas?

i do use jQuery 1.8.0

mymy.js does contain a function:

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 **/
});

解决方案

readCookie is undefined because readCookie is not global; it is visible only within the document.ready function scope in mymy.js.

Make the function global by removing the document.ready wrapper.

这篇关于jQuery.getScript()无法加载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆