【问题标题】:Cookie to hold multiple values including a variable?Cookie 保存多个值,包括一个变量?
【发布时间】:2013-12-15 02:38:37
【问题描述】:

我正在尝试在一个 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 和 opacity 与颜色名称一起存储在 cookie 中?

【问题讨论】:

    标签: javascript cookies


    【解决方案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 中存储值,请参阅 What is the "best" way to get and set a single cookie value using JavaScript

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多