javascript - 表达式 '$.cookie' [undefined] 的结果不是函数

标签 javascript jquery jquery-ui jquery-mobile cordova

大家好,在我的移动应用程序中,在没有 ajax 的情况下在各个页面之间传递变量我正在使用 cookie。我正在设置 cookie:

 $.cookie("userName", userName, { path: '/' });

在 js 文件和另一个 html 文件中,我访问它的方式是:

$.cookie('userName');

但我得到的错误是:

Result of expression '$.cookie' [undefined] is not a function

我有一个用于 cookie 的 js 文件:jquery.cookie.js 它包含以下代码:

/*jshint eqnull:true */
/*!
* jQuery Cookie Plugin v1.1
* https://github.com/carhartl/jquery-cookie
*
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($, document) {

var pluses = /\+/g;
function raw(s) {
    return s;
}
function decoded(s) {
    return decodeURIComponent(s.replace(pluses, ' '));
}

$.cookie = function(key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
        options = $.extend({}, $.cookie.defaults, options);

        if (value == null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path    ? '; path=' + options.path : '',
            options.domain  ? '; domain=' + options.domain : '',
            options.secure  ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || $.cookie.defaults || {};
    var decode = options.raw ? raw : decoded;
    var cookies = document.cookie.split('; ');
    for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
        if (decode(parts.shift()) === key) {
            return decode(parts.join('='));
        }
    }
    return null;
};

  $.cookie.defaults = {};

   })(jQuery, document);

我也在我的 html 文件中导入了上面的 js 文件。我也尝试过 setCookie('userName', 'userName', 1); 为什么会这样?任何建议将不胜感激。

最佳答案

确保您的 jquery.cookie.js 确实包含在内,并且在您调用 $.cookie() 之前它包含在内。

关于javascript - 表达式 '$.cookie' [undefined] 的结果不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558319/

相关文章:

javascript - javascript中的鼠标悬停事件不会输出

javascript - 当浏览器自动填写表单字段时,$parsers\$formatters 函数不会触发

javascript - setInterval 考虑运行的函数时间

jquery - 在哪里可以获得更多 jQuery UI 主题?

html - 为什么元素在 jquery-ui sortable 中重叠底部边框?

javascript - 一种方式流式传输 - 在添加候选项之前 ICE 连接失败

javascript - 嵌套变量不正确地递增

javascript - 如何创建没有名称的 "Empty"<Label> 标记

javascript - 针对点击事件的 Google DFP 广告展示

javascript - 比较 JQuery 中给定时间段之间的当前时间