我正在为基于浏览器的游戏创建一个保存对话框,我遇到了一些问题。我已经保存并列出了保存,但我遇到了加载,覆盖和删除的问题。我已经动态创建了保存条目,以及用于操作每个保存的按钮。单击任何按钮将打开一个确认对话框,单击是将执行实际操作。我的问题在于让每个操作实际上在相关的保存上运行。到目前为止我的代码看起来像这样:
var saveNum, buttonType;
function loadSaveList(){
saves = JSON.parse(localStorage.getItem("game_saves"));
for(var a=0; a < saves.length; a++){
var entry = document.createElement("div");
var buttons = document.createElement("div");
var overwriteB = document.createElement("input");
var deleteB = document.createElement("input");
var loadB = document.createElement("input");
overwriteB.type = "button";
deleteB.type = "button";
loadB.type = "button";
overwriteB.onclick = function(){buttonType = 0; saveNum = function(){return a;}; saveAlert();};
deleteB.onclick = function(){buttonType = 1; saveNum = function(){return a;}; saveAlert();};
loadB.onclick = function(){buttonType = 2; saveNum = function(){return a;}; saveAlert();};
buttons.appendChild(overwriteB);
buttons.appendChild(deleteB);
buttons.appendChild(loadB);
entry.appendChild(buttons);
document.getElementById("saveEntries").appendChild(entry);}}
function saveAlert(){
switch(buttonType){
case 0:
document.getElementById("alertYes").onclick = overwriteButton;
document.getElementById("alertNo").onclick = function(){/*styling to close alert*/}; break;
case 1:
document.getElementById("alertYes").onclick = deleteButton;
document.getElementById("alertNo").onclick = function(){/*styling to close alert*/}; break;
case 2:
document.getElementById("alertYes").onclick = loadButton;
document.getElementById("alertNo").onclick = function(){/*styling to close alert*/}; break;}}
function overwriteButton(){
unloadSaveList();
saves.splice(saveNum, 1, currentSave);
localStorage.setItem("game_saves", JSON.stringify(saves));
loadSaveList();}
function deleteButton(){
unloadSaveList();
saves.splice(saveNum, 1);
localStorage.setItem("game_saves", JSON.stringify(saves));
loadSaveList();}
function loadButton(){
var tempSave = saves.slice(saveNum, saveNum+1);
currentSaveLoad(tempSave);
unloadSaveList();
saves = [];}
我的意图是使用saveNum
来存储a
的值,以便底部的3个函数知道要操作哪个存储。我认为封闭是获得价值的方法,但我真的不太确定如何以一种可行的方式实现它。我主要寻找的是vanilla js的解决方案,但如果不这样做,我们会欢迎另一种解决问题的方法。
答案 0 :(得分:1)
男人,事实证明我是如此接近。我做了两个小改动:
我在for循环构造函数中将var
更改为let
:
for(let a=0; a < saves.length; a++){
我更改了saveNum
以接受a
本身的值:
loadB.onclick = function(){buttonType = 2; saveNum = a; saveAlert();};
感谢Hunter Frazier指出我正确的方向。