2015-09-03 28 views
0

的JavaScriptcookie檢查不是由輸入值工作

var dc = document.cookie; 
var nv = dc.split('; '); 
var cookie = new Object(); 

for(i = 0; i < nv.length; i++){ 
    eq = nv[i].indexOf('='); 
    cookie[nv[i].substring(0, eq)] = unescape(nv[i].substring(eq + 1)); 
} 

// type 1 
//this check is working 
if(cookie['name']){ 
    alert(document.cookie); 
    alert("this is avaliable"); 
}else{ 
    alert(document.cookie); 
    alert("this is not avaliable"); 
}; 

// type 2 
//this check is not working error undefined; 
function checkGroup(cn_name){ 
    document.cookie = cn_name; 
    alert(cookie[cn_name]); 
}; 

我使用cookie[]檢查是我的cookie avaliable,1型檢查工作,因爲我輸入廠的文本,但2型我試圖用價值在我的cookie[],它沒有工作。

如何讓它工作?

+0

我對鉻測試。 – user3233074

+0

我不這麼認爲,它checkGroup它返回我的undefined,你能幫我檢查一下嗎? – user3233074

+0

回答

0

你在哪裏運行腳本? 運行它當身體被加載時,代碼似乎對我來說很好

編輯:正如我說的評論,值'image_Group1'。您的Cookie []對象與鍵「image_Group1」沒有元素,這就是爲什麼你的函數返回undefined

記住,總是與格式鍵上創建的cookie =價值

供參考:https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

+0

我在onclick時運行它〜它工作嗎? – user3233074

+0

如果你做了一些像'document.cookie ='image_Group1'這樣的東西,那麼實際上創建的cookie就是一個cookie'key'和value'image_Group1'。 你的cookie []對象沒有鍵'image_Group1'的元素,這就是爲什麼你的函數返回undefined – gbalduzzi

+0

ohh?所以我要做什麼? – user3233074