javascript - Cookie 来保存多个值,包括一个变量?

标签 javascript cookies

我试图在 cookie 中保存多个变量,这是代码:

function changeColors(){
//get the numbers from the html
var rd = parseInt(document.getElementById("red").value);
var gr = parseInt(document.getElementById("green").value);
var bl = parseInt(document.getElementById("blue").value);
var op = parseFloat(document.getElementById("opacity").value);


//convert the decimal into hexadecimal

var rdhex = (rd < 16) ? "0" + rd.toString(16) : rd.toString(16);
var grhex = (gr < 16) ? "0" + gr.toString(16) : gr.toString(16);
var blhex = (bl < 16) ? "0" + bl.toString(16) : bl.toString(16);

//concatenate all hex to generate a color
var hexcode = "#" + rdhex + grhex + blhex;

//view the change in the browser
document.getElementById("div").style.backgroundColor = hexcode;
document.getElementById("colordisplay").innerHTML = hexcode;
//change opacity
document.getElementById("div").style.opacity = op;
}

function WriteCookie()
{
if( document.myform.name.value == "" ){
    alert("Enter some value!");
    return;
}

cookievalue= escape(document.myform.red.value) + ";" +
    escape(document.myform.red.value)+ ";"+
    escape(document.myform.green.value)+ ";"+
    escape(document.myform.blue.value)+ ";"+
    escape(document.myform.opacity.value)+ ";";
document.cookie="color=" + cookievalue;
alert("Setting Cookies : " + "color=" + cookievalue );

// To revise!!!How do we set multiple values to one cookie?
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );

// Get all the cookies pairs in an array
cookiearray  = allcookies.split(';');

我需要将名称、RGB 和不透明度存储在 cookie 中,以便以后用户可以从他自己管理的以前的颜色中进行选择。我的问题是如何将 var hexcode 和不透明度与颜色名称一起存储在 cookie 中?

最佳答案

您可以使用 join() 将值连接在一起,即:

var separator = ":" // or whatever
var values = [name, rgb, opacity].join(separator);

// then you store the values in a cookie
document.cookie = "myValues=" + values;

要在 cookie 中存储值,请参阅 What is the "best" way to get and set a single cookie value using JavaScript

关于javascript - Cookie 来保存多个值,包括一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586764/

相关文章:

angular - 无法读取某些 cookie

javascript - 无需刷新页面即可检测到cookie已被删除

java - 在 Java 中检索正确 cookie 的问题

javascript - 如何使用jQuery获取具有一定宽度的元素?

javascript - 构建时有什么方法可以使 Electron 在后台执行nodejs文件服务器吗?

javascript - 将字符串转换为变量名称以在 jQuery .animate 中使用

JavaScript 在 Cordova Visual Studio 2015 中无法工作

javascript - 使用 cookie 记住一篇文章是否已被阅读 - 需要注意的标识符

android - 将 cookie 存储在 sharedpreferences 中

javascript - React/Redux 中的生命游戏,有助于提高性能