使用本地存储重新加载页面时保存HTML类(隐藏)



我正在用纯HTML/JavaScript构建一个文本RPG。我用简单的存储设置了本地存储,让我的生活更轻松。也就是说,我遇到了一个关于宝箱的有趣问题。如果你打开了一个箱子,该功能会适当地隐藏按钮,以防止再次打开箱子。但是,如果您在保存后重新加载页面,胸部会重新出现!添加到胸部的类被移除,允许玩家再次从中拉出。由于他们的库存可以适当地节省,理论上他们可以得到无限的药剂。

HTML:

<button id="chest-1" onclick="openChest(potion, this.id)" onload="toggleChests()">Open Chest</button>

JS:

let opened = document.getElementsByClassName("opened"); opened.hidden = true;
function openChest(item, id){
inventory.push(item);
document.getElementById(id).hidden = true;
document.getElementById(id).classList.add("opened");
alert("You found: " + item.name + " - in the chest!");
simpleStorage.set("opened", opened);
};

当游戏加载时,它应该检查是否保存了胸脯类,如果保存了,则应用它。我认为这肯定是我出错的地方。

function toggleChests(){
opened = simpleStorage.get("opened", opened);
if (opened === true){
opened.hidden = true;
}
};

项目源代码:https://github.com/AndyDaMandy/Textia

多亏了Heretic Monkey和Cbroe的一些提示,我才明白了这一点。

我通过将每个打开的箱子的id串推入一个名为"的数组来解决这个问题;打开";。保存时,将保存阵列。加载时,打开的将被重新加载。然后,load函数调用applyOpened函数,然后该函数将.map应用于数组。它获取每个id并将其放入document.getElementById中,然后向其添加隐藏属性。这是在为玩家加载页面之前完成的,防止他们在不使用控制台的情况下访问元素(这将是欺骗!(。同样,简单的存储使它成为可能,所以我不需要将数组转换为字符串,但它也应该与常规本地存储一起工作!

这是代码:

let opened = []; 
function openChest(item, id){
inventory.push(item);
document.getElementById(id).hidden = true;
opened.push(id);
alert("You found: " + item.name + " - in the chest!"); 
};
function applyOpened () {
function apply(arr) {
document.getElementById(arr).hidden = true;
} 
opened.map(apply);
};
function save() {
simpleStorage.set("opened", opened);
};
function load(){
opened = simpleStorage.get("opened", opened);
applyOpened();
};

这是箱子的html:

<button id="chest-1" onclick="openChest(potion, this.id)">Open Chest</button>

最新更新