简体   繁体   中英

Javascript return value undefined

I would like to ask how to return variable 'get_cookies' from function 'save_value'. Then write its value in mouseleave event.

Function 'get_cookies' will save change from input. An error is in return i think.

Sorry for my bad English.

Here is code:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="jquery.cookie.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            function save_value(value) {
                var get_cookie = value;
                return get_cookie;
            };

            $('#submit_value').live('click', function() {
                var get_value = $('#get_value').val();
                save_value(get_value);
            });

            $(document).mouseleave(function() {
                var create_cookie = save_value();
                console.log('save: ' + create_cookie);
            });
        });
    </script>
</head>
<body>
    <input type="text" id="get_value" />
    <input type="button" id="submit_value" value="Click" />
    <div></div>
</body>

console log:

save: undefined

Thx for answer.

the function save_value() is expecting a parameter. Since here

var create_cookie = save_value();

you're not passing a value to the function, it will return undefined , thus the variable create_cookie value is undefined too

Your save_value() function requires an input parameter, so just save_value() on its own is undefined.

Did you mean to do this?

$(document).mouseleave(function() {
    var get_value = $('#get_value').val();
    var create_cookie = save_value(get_value);
    console.log('save: ' + create_cookie);
});

It's quite simple: your function function save_value(value) takes the value parameter, assigns it to a variable, and returns that variable. When you call it without parameters, like you do here: var create_cookie = save_value(); , the value argument will be undefined. Hence, the function returns undefined.

Also: using variables called cookie doesn't set a cookie. For that, you'll have to use localStorage.setItem('cookieName','cookieValue');

Since you are using latest jQuery version, you should not use live() function, since it has been deprecated in jQuery 1.7.

Anyway, your issue is different. Your save_value function does nothing. Just creating a variable and returning its value. But you do not pass any arguments, so it returns default value: undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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