0

有人可以帮助我完成我需要的两个功能。我想要一个函数从 cookie 字符串中获取属性值,以匹配控件 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;
}
4

1 回答 1

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);
于 2013-07-08T15:52:20.823 回答