0

所以我有一个简单的会话 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>
4

1 回答 1

0
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.')
于 2012-09-22T18:18:06.920 回答