Cookie包含多个值,包括变量?

 时间熔金-岁月铅华_758 发布于 2023-02-10 13:53

我试图在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(';');

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

1 个回答
  • 您可以将这些值一起加入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中存储值,请参阅使用JavaScript获取和设置单个cookie值的"最佳"方法

    2023-02-10 13:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有