【问题标题】:How to Create Cookies to Remember a Javascript Instruction如何创建 Cookie 以记住 Javascript 指令
【发布时间】:2011-03-12 06:19:48
【问题描述】:

为了在我的网站上实现“关闭样式”按钮(用于大学作业),John Giotta 之前好心地给了我这段代码(堆栈溢出)。

function nostyle() {
    for (i=0; i<document.styleSheets.length; i++) {
        void(document.styleSheets.item(i).disabled=true);
    }
} 

我想知道实现一个 cookie 是多么容易记住这个 javascript 已被应用,以便在网站上导航的每个页面都关闭样式(我的知识是非常基本的,我只是一年级)。

问候

【问题讨论】:

  • 确保var您的变量,这样您就不会设置全局变量。在 for 循环中,它应该是 var i = 0 而不是 i = 0

标签: javascript html css cookies


【解决方案1】:
function SetCookie(cookieName,cookieValue,nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue)
        + ";expires="+expire.toGMTString();
}

设置你的css_disabled cookie

SetCookie('css_disabled', 'true', 100);

读取 cookie:

function ReadCookie(cookieName) {
    var theCookie=""+document.cookie;
    var ind=theCookie.indexOf(cookieName+"=");
    if (ind==-1 || cookieName=="") return "";
    var ind1=theCookie.indexOf(";",ind);
    if (ind1==-1) ind1=theCookie.length; 
    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

if (ReadCookie('css_disabled') == 'true') {...

【讨论】:

  • 谢谢,但是我如何在我的代码中实现它,这比我们今年所涵盖的内容高出两年,我只是对它的工作方式感兴趣,我会将设置的 cookie 保存为css_disable 然后.....
  • 您需要在页面加载时首先读取 cookie。如果未设置 cookie,您将得到一个空字符串并且您不会禁用。如果当用户禁用 CSS 时,请将 cookie 设置为 true。
猜你喜欢
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
相关资源
最近更新 更多