2014-12-05 42 views
0

这是我的第二个jQuery项目,我试图做一种简单的选择你自己的冒险游戏。它所用的类已经涵盖了开始的html,css和jquery。我正在尝试创建一个系统,可以根据点击将项目添加到数组,然后将该数组的内容显示为用户的“库存”。该阵列也需要存储在本地。我有什么至今:编辑 - 本地存储的变量不工作

新的东西在这里

**感谢您的答复,我收到了前几天。我尝试了解这些答案,并且还与导师交谈了一下​​,并改变了我的一些方法。然而,事情并没有真正起作用,我不知道为什么。这是我的新代码到目前为止:*

$(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. 

}); 

谢谢你看看。我没有足够的经验来善于查找错误。

+1

看,用于本地存储的值... – 2014-12-05 05:43:15

回答

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"); 
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>"); 
} 

演示拿回你的存储阵列:在localStorage的Fiddle