【问题标题】:$.cookie giving error : Uncaught TypeError$.cookie 给出错误:未捕获的 TypeError
【发布时间】:2013-11-07 04:18:09
【问题描述】:

我正在写一个js文件

    checkCookiesAccepted();

    function checkCookiesAccepted() {
        if (!$.cookie("acecptcookies")) {
            showCookieBar();
            attachPageChangedEvents();
        }
    }


function attachPageChangedEvents(){
            // get all internal a hrefs and override onclick event so we can record acceptance
            var siteURL = "http://" + top.location.host.toString();

            //$("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']").click(acceptCookies);
            $("#middle a").click(acceptCookies);
        }
function acceptCookies(){
            $.cookie("acecptcookies", "1", { path: '/', expires: 20*365 });

        }
        function showCookieBar(){
            // create div elements to body element unless another is supplied
            $("<div id='tscookiebar'><div>This site uses cookies. To find out more about the cookies this site uses and how to manage them, please review the cookies section of our <a href='http://www.myproduct.co.uk/privacy_policy/PrivacyPolicy.pdf' target='_blank'>Privacy Policy</a>. By using our website, you agree that we can place these types of cookies on your device.</div></div>").prependTo("body");
        }
        $.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 || value === undefined)) {
                        options = $.extend({}, options);

                        if (value === null || value === undefined) {
                            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 || {};
                    var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

                    var pairs = document.cookie.split('; ');
                    for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
                        if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
                    }
                    return null;
                };

我还包括 jquery.min.js 和 jquery.cookie.js 但仍然报错 未捕获的类型错误:对象函数 (e,t){return new x.fn.init(e,t,r)} 没有方法 'cookie'

【问题讨论】:

  • 您是否添加了对jquery-cookie 的引用?插件加载了吗?
  • 与问题无关,但请注意acecptcookies的错字
  • 使用下面的 jsFiddle 你能把这个问题说得更清楚吗? jsfiddle.net/cQfjS
  • 如果您正确添加了jquery.cookie.js,那么您的代码应该没有问题。问题是因为插件没有加载。
  • 另外,你可以像if($.cookie &amp;&amp; !$.cookie("acecptcookies")) {这样修改代码,确保只有在包含cookie插件的情况下才会执行代码!

标签: javascript jquery


【解决方案1】:

给出一个错误 Uncaught TypeError: Object function (e,t){return new x.fn.init(e,t,r)} has no method 'cookie'

好的,这告诉我们您确实加载了 jQuery(因为这就是缩小的 jQuery 函数的样子)并且 jQuery 使用了$ 符号,但出于某种原因,cookie 插件-in 在您运行该代码时不存在于 jQuery 函数中。可能的原因:

  1. 您的 cookie 插件路径不正确,您收到的是 404。

  2. 您在加载 cookie 插件之后 加载 jQuery,可能是第一次(jquery.min.jsjquery.cookie.js 之后),或者您不小心将其加载到 第二次次,覆盖第一次。

  3. 您正在运行代码加载 jQuery 但加载 cookie 插件之前。

  4. script 标签的顺序正确,因为您在它们上使用了the async attribute,因此它们被乱序执行。

  5. 您正在使用代码(而不是标记)添加 script 元素。当您使用代码而不是标记添加脚本时,它们的执行顺序无法保证。

如果你有这个:

<script src="/path/jquery.min.js"></script>
<script src="/path/jquery.cookie.js"></script>
<script src="/path/your.script.js"></script>

...您没有收到任何 404 错误,它应该可以工作。

【讨论】:

    【解决方案2】:

    Demo jsFiddle

    说明

    一切似乎都按预期工作。


    JS

    $(function(){
        checkCookiesAccepted();
    });
    
    function checkCookiesAccepted() {
        if (!$.cookie("acecptcookies")) {
            showCookieBar();
            attachPageChangedEvents();
        }
    }
    
    
    function attachPageChangedEvents() {
        // get all internal a hrefs and override onclick event so we can record acceptance
        var siteURL = "http://" + top.location.host.toString();
    
        //$("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']").click(acceptCookies);
        $("#middle a").click(acceptCookies);
    }
    
    function acceptCookies() {
        $.cookie("acecptcookies", "1", {
            path: '/',
            expires: 20 * 365
        });
    
    }
    
    function showCookieBar() {
        // create div elements to body element unless another is supplied
        $("<div id='tscookiebar'><div>This site uses cookies. To find out more about the cookies this site uses and how to manage them, please review the cookies section of our <a href='http://www.msdproduct.co.uk/privacy_policy/PrivacyPolicy.pdf' target='_blank'>Privacy Policy</a>. By using our website, you agree that we can place these types of cookies on your device.</div></div>").prependTo("body");
    }
    $.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 || value === undefined)) {
            options = $.extend({}, options);
    
            if (value === null || value === undefined) {
                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 || {};
        var decode = options.raw ? function (s) {
            return s;
        } : decodeURIComponent;
    
        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2019-04-20
      • 2018-01-21
      • 2021-11-02
      • 2020-02-15
      • 2016-03-21
      相关资源
      最近更新 更多