2014-12-05 73 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