我正在制作一个基于文本的javascript和html游戏,您必须在其中收集物品。用户可以进入游戏的每个位置都有一个html页面,他们可以在两个位置之间自由移动。
我为库存创建了一个空数组,并创建了一个函数,该函数确定用户是否已在该位置拾取了物品。
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.")
};
但是,当我离开页面并返回该位置时,它不记得推送到库存中的项目了。
有什么简单的方法可以使程序记住页面之间以及返回位置时的更新清单?
谢谢。
最佳答案
实际上,当您离开html页面时,所有的javascript var都会被删除,一种绕过此操作的好方法是使用AJAX(使用jQuery)。
您有自己的页面,并且在每个链接上,而不是
<a href="mypage.html"> Link </a>
用
<a onclick="$('#main').load('mypage.html');" href="#"> Link </a>
然后,将保留您所有的JavaScript var(包括数组)。
(显然,您需要将所有代码放在
<div id="main"></div>
之间,否则,将不起作用!:p