简体   繁体   English

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

[英]jQuery Plugin Function Returning Undefined For The Value

I created a jQuery plugin to do various things with cookies. 我创建了一个jQuery插件来处理Cookie。 The trouble I am having is the function I created to read the cookie and return the value. 我遇到的麻烦是我创建的用于读取cookie并返回值的函数。 No matter what I do, when I call the function as so from the main page 不管我做什么,当我从主页调用函数时

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

the return is ALWAYS undefined. 返回值始终是不确定的。 Console output is as follows: 控制台输出如下:

Value found is => 10
Returned => undefined

I'm at my wit's end trying to figure out what's going on here. 我尽力想弄清楚这里发生了什么。 I've tried everything I know to do and spent literally hours Googling this with no solution. 我已经尝试了所有我想做的事情,并且花了数小时来搜索,没有解决方案。 Below is the code in my jQuery plugin: 以下是我的jQuery插件中的代码:

// Get the value of the sought after cookie //获取所需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; } } 

Does anyone have any insight into what's causing this and how it can be corrected? 是否有人对导致此问题的原因以及如何纠正它有任何见解?

Here is the entire code of my jQuery plugin 这是我的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: 解:

Thanks to OJay below for the keen eye and the solution to this. 感谢下面的OJay敏锐的眼光和解决方案。 Scroll down and give him some upvotes. 向下滚动并给他一些投票。

The call to get_cookie() in the main switch statement that handles what action to take was not returning anything. 在主switch语句中对get_cookie()的调用get_cookie()该调用处理了要执行的操作)没有返回任何内容。 So following OJay 's solution it now works by looking like this: 因此,遵循OJay的解决方案,它现在可以像下面这样工作:

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

inside your cookie 'plugin', you do a case statement on the action, and call the corresponding private method. 在Cookie“插件”中,您对操作执行了case语句,并调用了相应的private方法。 Now the get method returns a value, but you are not doing anything with it, the return value of get is not being returned by the parent function 现在,get方法返回一个值,但是您并未对其执行任何操作,get函数的返回值未由父函数返回

ie

 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
    }

This will mean that the parent function ($.cookie) doesn't have a return statement in it for get, so returns undefined (default javascript behavior) 这意味着父函数($ .cookie)中没有用于获取的return语句,因此返回未定义(默认javascript行为)

Return the value of the get action, like you did with the "check" one. 返回get操作的值,就像您对"check"操作所做的一样。

It doesn't have a return value for "create" or "delete" either, but they don't necessarily need to. 它也没有"create""delete"的返回值,但是它们不一定需要。 Although I would probably return a boolean (true or false) to indicate that the create or delete was successful 尽管我可能会返回一个布尔值(true或false)以指示创建或删除成功

Check if the symbol $ is defined and check if the symbol jQuery is defined. 检查符号$是否已定义,以及符号jQuery是否已定义。 if $ is not defined and jQuery is, try jQuery.cookie instead of $.cookie . 如果未定义$jQuery是,请尝试使用jQuery.cookie而不是$.cookie

If both are undefined, I would check if the jQuery scripts are included in your HTML code. 如果两者均未定义,我将检查HTML代码中是否包含jQuery脚本。 One of the ways to include jQuery is described here . 这里介绍包括jQuery一种方法。 Look for something like <script src="jquery.. in your page's HTML code to see if it is already included. If it is not, you should include it. The scripts should be included before you try to use $ or jQuery symbols 在页面的HTML代码中查找类似<script src="jquery.. ,以查看是否已包含该脚本。如果尚未包含,则应包含它。在尝试使用$jQuery符号之前,应包含这些脚本。

Try defining your plugin using 尝试使用定义您的插件

$.fn.cookie = function(options) {
    //... your plugin
}

according to the jquery documentation 根据jQuery 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM