2013-07-05 56 views
0

有人可以幫助我需要兩個函數。我想要一個函數從cookie字符串中獲取屬性值,並且與控件ID相匹配,另一個函數爲控件ID設置屬性值。我的字符串如下所示Cookie字符串獲取並設置jQuery控件的屬性

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; 
} 

回答

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);