cookie字符串获取和设置jquery控件的属性

时间:2013-07-05 03:20:33

标签: javascript jquery

有人可以帮助我完成我需要的两个功能。我想要一个函数从cookie字符串获取属性值taht匹配控件id,另一个函数为控件id设置属性值。我的字符串看起来像这样

var cookieValue='id=1&state=normal&theme=purple:id=2&state=maximized&theme=pink';

对于每个控件属性,必须使用冒号cookieValue.split(':')拆分字符串;并且在设置propertyValue时,必须更新cookieString并将其连接在一起,是否有人知道如何执行此操作。

函数看起来像这样

function setPropertyValue(cookieString, id,  propertyName, propertyValue) {
    if(id) setProperty_Value
    return cookieString;
}

function getPropertyValue(cookieString, id, proprtyName) {
     return propertyValue;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

function setPropertyValue(cookieString, id,  propertyName, propertyValue) {
  cookieObjects = cookieString.split(':');
  for (var i = 0; i < cookieObjects.length; i++)
  {
    cookieObject = cookieObjects[i];
    if (cookieObject.indexOf("id=" + id) >= 0)
    {
      cookieProperties = cookieObject.split("&");
      for (var j = 0; j < cookieProperties.length; j++)
      {
        cookieProperty = cookieProperties[j];
        if (cookieProperty.indexOf(propertyName) >= 0)
        {
          return cookieString.replace(cookieProperty, cookieProperty.split("=")[0] + "=" + propertyValue);
        }
      }
    }
  }
  return propertyValue;
}

function getPropertyValue(cookieString, id, propertyName) {
  cookieObjects = cookieString.split(':');
  for (var i = 0; i < cookieObjects.length; i++)
  {
    cookieObject = cookieObjects[i];
    if (cookieObject.indexOf("id=" + id) >= 0)
    {
      cookieProperties = cookieObject.split("&");
      for (var j = 0; j < cookieProperties.length; j++)
      {
        cookieProperty = cookieProperties[j];
        if (cookieProperty.indexOf(propertyName) >= 0)
        {
          return cookieProperty.split("=")[1];
        }
      }
    }
  }
  return propertyValue;
}

var cookieValue='id=1&state=normal&theme=purple:id=2&state=maximized&theme=pink';

alert(getPropertyValue(cookieValue, "1", "state"));
cookieValue = setPropertyValue(cookieValue, "1", "state", "not");
alert(cookieValue);