最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - $.cookie giving error : Uncaught TypeError - Stack Overflow

programmeradmin1浏览0评论

I am writing a js file

    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='.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;
                };

i also include jquery.min.js and jquery.cookie.js but still giving an error Uncaught TypeError: Object function (e,t){return new x.fn.init(e,t,r)} has no method 'cookie'

I am writing a js file

    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;
                };

i also include jquery.min.js and jquery.cookie.js but still giving an error Uncaught TypeError: Object function (e,t){return new x.fn.init(e,t,r)} has no method 'cookie'

Share Improve this question edited Oct 28, 2013 at 12:09 AmateurCoder asked Oct 28, 2013 at 11:46 AmateurCoderAmateurCoder 4,3123 gold badges18 silver badges31 bronze badges 10
  • 1 Have you added reference to jquery-cookie? Is plugin loaded? – Satpal Commented Oct 28, 2013 at 11:48
  • 3 Not related to the question, but watch out for that typo at acecptcookies – orique Commented Oct 28, 2013 at 11:49
  • using the following jsFiddle can you please make this question more clear? jsfiddle/cQfjS – abc123 Commented Oct 28, 2013 at 11:49
  • If you have correctly added jquery.cookie.js then there should be no issues with your code. The problem is because the plugin has not been loaded. – Rory McCrossan Commented Oct 28, 2013 at 11:51
  • Also, you can modify the code like if($.cookie && !$.cookie("acecptcookies")) { to make sure that the code is executed only if the cookie plugin is included! – palaѕн Commented Oct 28, 2013 at 11:55
 |  Show 5 more ments

2 Answers 2

Reset to default 7

giving an error Uncaught TypeError: Object function (e,t){return new x.fn.init(e,t,r)} has no method 'cookie'

Okay, this tells us that you do have jQuery loaded (as that's what the minified jQuery function looks like) and jQuery is using the $ symbol, but for some reason, the cookie plug-in does not exist on the jQuery function as of when you're running that code. Possible reasons:

  1. Your path to the cookie plug-in is incorrect and you're getting a 404.

  2. You're loading jQuery after loading the cookie plug-in, either the first time (jquery.min.js is after jquery.cookie.js) or you're accidentally loading it a second time, overwriting the first.

  3. You're running your code after loading jQuery but before loading the cookie plug-in.

  4. You have the script tags in the right order, by you've used the async attribute on them, and so they're being executed out of order.

  5. You're adding the script elements using code (not markup). When you add scripts using code rather than markup, their execution order is not guaranteed.

If you have this:

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

...and you're not getting any 404 errors, it should work.

Demo jsFiddle

Description

Everything appears to be working as intended.


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;
};
发布评论

评论列表(0)

  1. 暂无评论