2016-05-29 35 views
1

我正在製作一個基於文本的javascript和html遊戲,您必須收集項目。遊戲中的每個位置都有一個HTML頁面,用戶可以在這些位置之間自由移動。js更新函數中的數組

我已經爲庫存和一個函數確定用戶是否已經拿起該位置的物品。

function fieldItems() { 
if (inventory.indexOf("paper") === -1 && inventory.indexOf("string") === -1) { 
    var fieldItems= prompt("There is string and paper \n Do you: \n A -pick up the paper \n B -take the string \n C -take both \n D -leave both").toUpperCase(); 
} else if (inventory.indexOf("string") === -1){ 
    var fieldItems= prompt("There is string. \n Do you: \n B -take the string \n D -leave it").toUpperCase(); 
} else if (inventory.indexOf("paper") === -1) { 
    var fieldItems= prompt("There is paper\n Do you: \n A -pick up the paper \n D -leave it").toUpperCase(); 
} else { 
    confirm("The field is empty."); 
}; 
if (fieldItems === "A") { 
    inventory.push("paper"); 
    confirm("You pick up the piece of paper."); 
} else if (fieldItems === "B") { 
    inventory.push("string"); 
    confirm("You take the string."); 
} else if (fieldItems === "C") { 
    inventory.push("paper"); 
    confirm("You pick up the piece of paper."); 
    inventory.push("string"); 
    confirm("You take the string."); 
} else { 
    confirm("You do not pick anything up.") 
}; 

但是,當我離開頁面並返回到該位置時,它不記得推送到庫存的項目。

有沒有簡單的方法讓程序記住頁面之間的更新清單以及何時返回到位置?

謝謝。

+2

[localStorage的(https://developer.mozilla.org/en-US/docs/ Web/API/Window/localStorage) –

+0

javascript中的變量值適用於定義頁面的頁面,通過這種方式不能跨頁面值傳遞 –

回答

0

實際上,當你離開一個html頁面時,所有的javascript變量都被刪除了,一種很好的繞過這個方法就是使用AJAX(帶有jQuery)。

你有你的頁面,每一個環節上,而不是

<a href="mypage.html"> Link </a> 

使用

<a onclick="$('#main').load('mypage.html');" href="#"> Link </a> 

然後,所有你的JavaScript瓦爾(包括數組)將被保留。

(顯然,你需要把<div id="main"></div>之間所有的代碼,如果沒有,它不會工作:P!