简体   繁体   English

Javascript Cookie函数

[英]Javascript Cookie function

I have an question relating to my cookie function. 我有一个与Cookie功能有关的问题。 Does it really have to have the $(function) for the if(readCookie) or can I specify just function like the rest of the code above it? 它是否真的必须为if(readCookie)提供$(function),还是可以像上面的其余代码一样指定函数? I've tried setting it a few different ways but without the $function it doesn't read the set cookie. 我尝试用几种不同的方式设置它,但是如果没有$ function,它不会读取设置的cookie。 Can anybody help put me in the right direction. 谁能帮助我朝正确的方向发展。 Thank you. 谢谢。

    <script>
    function createCookie(name, value, days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }`enter code here`
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }

    function eraseCookie(name) {
    createCookie(name, "", -1);
    }

    $(function(){

    if(readCookie("style") == 'Dark'){
        $("body").removeClass().addClass("colour-scheme-1");         
        $(".styleswitch a").removeClass().addClass("Dark");
    }
    else {
    }

   });
    </script>

Yes, that's required. 是的,这是必需的。 What that's doing is deferring execution of the code in that function until after the DOM has been completely built. 这样做是将在该函数中执行代码的时间推迟到完全构建DOM之后。 If you didn't have that, then depending on exactly where on the page that script is imported it might not work at all. 如果您没有该脚本,则可能完全无法执行脚本,具体取决于该脚本在页面上的导入位置。

If you were to move the whole <script> block to the very end of the <body> , it'd work without the jQuery "ready" setup. 如果要将整个<script>块移到<body>末尾,则可以在没有jQuery“ ready”设置的情况下使用。

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

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