【问题标题】:parsing cookie values to if/elseif in javascript在javascript中将cookie值解析为if/else if
【发布时间】:2012-09-23 02:18:06
【问题描述】:

所以我有一个简单的会话 cookie 检索器,并将 cookie 值写入页面。只有两个值,“是”和“否”,否则返回 null。目前,它检查是否有值,如果有,则将该值写入页面。如何告诉脚本有条件地写入值(即,写入“是”,因为该值是“是”,与“否”相同,而不是仅仅传递响应)而不是它是否存在?

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

...

<p>
Response 1: 
<script>
var res1 = readCookie('res1')
if (res1) {
    document.write('res1')
}
else {
document.write("You did not respond.")
};
</script>
</p>

【问题讨论】:

  • 所以如果是,你想返回是,如果不是,你想返回否?

标签: javascript cookies session-cookies if-statement


【解决方案1】:
function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ))
    return matches ? decodeURIComponent(matches[1]) : undefined
}

document.write(getCookie('res1') != undefined ? 'res1' : 'You did not respond.')

【讨论】:

  • 这让我更接近,但不是我想要的。问题是我需要能够更改任何 document.write 的特定值。即使这不起作用,这更像是我想做的事情:if (res1) c = "Yes" { document.write("Yes") } else if (res1) c = "No" { document.write("No") } else { document.write("You did not respond.") };
  • 你有 Cookie 变量 res1 的值。当变量不存在时, res1 将是未定义的。想写条件有什么问题?
  • 对不起,res1 不是变量,它是 cookie 的名称。该变量正在被readCookie(name) 解析——所以我会调用readCookie(res1),它会返回res1 的值。但我需要为不同的值设置条件。
  • res1 = readCookie('res1'); if(res1 == 'Yes'){}else if(res1 == 'NO'){} else {}
  • 谢谢。我知道有办法做到这一点,但我无法正确使用语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2011-02-24
相关资源
最近更新 更多