这是我的第二个jquery项目,我正在努力做一个简单的选择你自己的冒险游戏。它所用的类包含了开头的html,css和jquery。我正在尝试创建一个系统,我可以根据点击次数将项目添加到数组中,然后以用户"库存"显示该数组的内容。该阵列也需要本地存储。到目前为止我所拥有的:
NEW STUFF HERE
**感谢您几天前收到的回复。我尝试使用这些答案,并且稍微与导师交谈并改变了我的一些方法。然而事情并没有真正起作用,我无法弄清楚原因。到目前为止,这是我的新代码:*
$(document).ready(function() {
//$(document).keydown(function(event) {
//alert("Hello"); });
//^ alert is a test to see if the files are hooked up right
if (localStorage.getItem("lightp") === null) {
localStorage.setItem("lightp", 0);
}
localStorage.getItem("lightp")
$( ".light" ).click(function() {
lightp++;
localStorage.setItem("lightp",lightp);
});
var light= localStorage.getItem("lightp");
if (light > 0) { alert("Hello") };
//^this is intended to create a locally stored variable that i can use to keep track of clicks as the user navigates the game. The alert is supposed to try to test if the number is actually increasing but either it doesn't work or I wrote something wrong or both.
$(".rope").click(function (event) { localStorage.setItem("hasRope",true)});
if (localStorage.getItem("hasRope") ===true){("#inventory").append("<p>Rope</p>")};
//^ since there are very few items in my game, my tutor suggested instead of trying to work an array I just use an individual local variable for each item. This is supposed to create the localStorage item when you click on the "rope" class link. The the script is supposed to check if the "rope" localStorage is defined and if it is, append the "rope" <p> into a div with the id "inventory", but that doesn't seem to work either.
});
谢谢你看看。我还没有足够的经验来擅长捕捉虫虫。
答案 0 :(得分:0)
您必须按索引
访问字符串for (var i = 0; i < inv.length; i++) {
$("#inventory").append("<p> contents of inv[0] = "+ inv[i] + "</p>");
}
localStorage.setItem("inv", inv); // store it locally
您也可以使用
$('#inventory').append("<p> contents of inv = " + inv.join(",") + "</p>");`
通过您选择的分隔符加入数组。你可以通过
取回存储的数组var arr = localStorage.getItem("inv");
答案 1 :(得分:0)
您可以执行类似
的操作//read the already stored value
var strInv = localStorage.getItem('inventory');
var inv = strInv ? JSON.parse(strInv) : [];
$(".rope").click(function (event) {
//some text to the stored/shown
var string = $('#input').val();
//if no value is entered, don't do anything
if (!string) {
return;
}
inv.push(string);
//add the new value to inventory
$("#inventory").append("<p>" + string + " </p>");
//store the updated array
localStorage.setItem('inventory', JSON.stringify(inv));
});
//Set the initial values
for (var i = 0; i < inv.length; i++) {
$("#inventory").append("<p>" + inv[i] + "</p>");
}
演示:Fiddle