jQuery插件函数返回未定义的值

时间:2014-08-07 20:18:03

标签: javascript jquery jquery-plugins

我创建了一个jQuery插件来使用Cookie执行各种操作。我遇到的麻烦是我创建的用于读取cookie并返回值的函数。无论我做什么,当我从主页面调用该函数时

test = $.cookie({
        action:'get', 
        cookie_name:LOGIN_COOKIE_NAME
    });

返回始终未定义。控制台输出如下:

Value found is => 10
Returned => undefined

我在我的智慧结束时试图弄清楚这里发生了什么。我已经尝试过我所知道的所有事情并花了几个小时在Google上搜索没有解决方案。下面是我的jQuery插件中的代码:

  

//获取被追捧的cookie的价值

    function get_cookie(){
      var value = '';
      // Get the name to search for
      var name = settings.cookie_name;

      // Divide the cookie string into an array
      var ca = document.cookie.split(';');

      // Loop through each element in the main array we just created
      match_found = false;
      for(var i=0; i<ca.length; i++){
          // Clear the whitespace from the ends to prevent mismatches and split each > element into the cookie name and value
          var temp = ca[i].trim().split('=');

          // Now check to see if this is the cookie we are looking for
          if(temp[0] == name && !match_found){
              match_found = true;
              // If it is, then return the cookie's value
              cookie_value = temp[1]+'';
              if(settings.action != 'check'){
                  value = cookie_value;
              }else{
                  value = true;
              }
          }
      }
      if(!match_found && settings.action == 'check'){
          return false;
      }else if(!match_found && settings.action != 'check'){
          return 'dooby';
      }else{
          console.log('Value found is => '+value);
          return value;
      }
    }

有没有人能够了解造成这种情况的原因以及如何纠正?

以下是我的jQuery插件的完整代码

(function($){
$.cookie = function(options) {

    // Default Settings
    var settings = $.extend({
        action : 'check', // create or delete
        cookie_name : 'cookie',
        cookie_value : 'default',
        expiration : 'Sun, 31 Dec 2017 12:00:00 GMT',
        path : '/'
    }, options);

    switch(settings.action){
        case "create":
            create_cookie();
            break;
        case "delete":
            delete_cookie();
            break;
        case "check":
            return check_for_cookie();
            break;
        case "get":
            get_cookie();
            break;
        default:
            get_cookie();
            break;
    }






    // Create the cookie
    function create_cookie(){
        try{
            document.cookie = settings.cookie_name+"="+settings.cookie_value+"; expires="+settings.expiration+"; path="+settings.path;
            console.log("Cookie Created");
        }catch(e){
            console.log(e);
        }
    }


    // Delete said cookie
    function delete_cookie(){
        document.cookie = settings.cookie_name+"="+settings.cookie_value+"; expires=Sun, 29 Dec 2013 12:00:00 GMT; path="+settings.path;
    }


    // Get the value of the sought after cookie
    function get_cookie(){
        var value = '';
        // Get the name to search for
        var name = settings.cookie_name;

        // Divide the cookie string into an array
        var ca = document.cookie.split(';');

        // Loop through each element in the main array we just created
        match_found = false;
        for(var i=0; i<ca.length; i++){
            // Clear the whitespace from the ends to prevent mismatches and split each element into the cookie name and value
            var temp = ca[i].trim().split('=');

            // Now check to see if this is the cookie we are looking for
            if(temp[0] == name && !match_found){
                match_found = true;
                // If it is, then return the cookie's value
                cookie_value = temp[1]+'';
                if(settings.action != 'check'){
                    value = cookie_value;
                }else{
                    value = true;
                }
            }
        }
        if(!match_found && settings.action == 'check'){
            return false;
        }else if(!match_found && settings.action != 'check'){
            return 'dooby';
        }else{
            console.log('Value found is => '+value);
            return value;
        }
    }


    // Check to see if said cookie exists
    function check_for_cookie(){
        var is_set = get_cookie(settings.cookie_name);
        if(is_set){
            return true;
        }else{
            return false;
        }
    }
};
}(jQuery));

SOLUTION:

感谢下面的OJay敏锐的眼光和解决方案。向下滚动并给他一些赞成。

主switch语句中对get_cookie()的调用处理要采取的操作并未返回任何内容。因此,按照OJay的解决方案,它现在的工作原理如下:

case "get":
    return get_cookie();
    break;

3 个答案:

答案 0 :(得分:1)

在您的Cookie'插件'中,您对该操作执行case语句,并调用相应的私有方法。现在get方法返回一个值,但是你没有对它做任何事情,父函数没有返回get的返回值

 switch(settings.action){
        ///... snipped for brevity
        case "get":
            //the get_cookie returns something, but you are not returning it past here
            get_cookie(); 
            break;
        ///... snipped for brevity
    }

这意味着父函数($ .cookie)在get中没有返回语句,因此返回undefined(默认的javascript行为)

返回get操作的值,就像使用"check"一样。

它也没有"create""delete"的返回值,但它们不一定需要。虽然我可能会返回一个布尔值(true或false)来表示创建或删除是否成功

答案 1 :(得分:0)

检查是否定义了符号$并检查是否定义了符号jQuery。如果未定义$jQueryjQuery.cookie,请尝试$.cookie而不是jQuery

如果两者都未定义,我会检查HTML代码中是否包含jQuery脚本。 其中一种包含<script src="jquery..的方法是here。 在页面的HTML代码中查找$之类的内容,以查看它是否已包含在内。如果不是,您应该包含它。 在尝试使用jQuery或{{1}}符号

之前,应包含脚本

答案 2 :(得分:0)

尝试使用

定义插件
$.fn.cookie = function(options) {
    //... your plugin
}

根据jquery documentation

相关问题