javascript 从变量设置 cookie 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14402630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:32:30  来源:igfitidea点击:

Set cookie value from variable

javascripthtmlcookies

提问by Blob

I have been recently trying to set a cookie holding the user's name, it opens a prompt pop-up box asking for a new user name. When the user inserts the user name and clicks "ok" it doesn't treat the variable (sconName) as a variable and just puts "sconName".

我最近一直在尝试设置一个包含用户名的 cookie,它会打开一个提示弹出框,要求输入新的用户名。当用户插入用户名并单击“确定”时,它不会将变量 (sconName) 视为变量,而只是输入“sconName”。

Note: Scon is the name of the website.

注意:Scon 是网站的名称。

Heres the only script I am using:

这是我使用的唯一脚本:

<html>
  <body>
<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>
<script>
  var username = readCookie('sconName');
if (username) {
   document.write("Your current username is: " + username);
}
  else {
    document.write("You have no user name");
  }

  function changeUsername() {
    var changedName=prompt("Enter user name.");
    if (changedName) {
document.cookie = 'sconName=changedName; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/'}}
  </script>
<button onclick="changeUsername()">Change</button>
</body>
</html>

Please can you explain how to tell the system that its a variable not just text. Thanks.

请您解释一下如何告诉系统它是一个变量而不仅仅是文本。谢谢。

回答by Crayon Violent

javascript does not parse variables inside quotes. You need to break out of the quotes to use the variable:

javascript 不解析引号内的变量。您需要打破引号以使用变量:

document.cookie = 'sconName='+changedName+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/'