2013-05-31 22 views
0

我正在使用jQuerymobile,並且我有一個listview。在列表視圖中,我有從localStorage加載的動態內容。當您單擊特定的listitem時,我希望用戶轉到下一個頁面,該頁面是來自該特定localstorage對象的關聯值。是否有可能加載和組合動態字符串到localStorage.getItem()?

我可以讓我的代碼在下面工作(我已經評論過)。問題是,

var favoritedName = JSON.parse(localStorage.getItem(placesText)); 

返回NULL。

但是如果我手動加載

var favoritedName = JSON.parse(localStorage.getItem("placesFireside Bar")); 

它工作正常。

我想知道,如果你可以動態加載.text()從listitem你點擊一個列表視圖,然後將其設置爲localstorage.getItem()中的鍵。

這裏是我的代碼:

// click the list item, which is a specific bar 
$('#all-my-favorites li').click(function() { 

// get specific name of Bar from the list item 
listitemText = $(this).text(); 

// OR manually name the list item. example here is "Fireside Bar" for testing purposes 
//listitemText = "Fireside Bar"; 

// combine the strings, so i can search localstorage for the relevant key item 
placesText = "places" + listitemText; 
//alert(placesText); 
// returns "placesFireside Bar" or "places(barname from listitem)" 

}); 

// go to the new page, which should show content from the relevant key item 
$('#favorited').on('pagebeforeshow', function() { 

// test to see if placesText is a string 
alert(jQuery.type(placesText) === "string"); 
// returns TRUE 

// find the relevant keyitem from localstorage, and name the object favoritedName 
var favoritedName = JSON.parse(localStorage.getItem(placesText)); 
alert(favoritedName); 
// returns NULL 

$(this).find('[data-role=header] .ui-title').text(favoritedName.name); 
$('#FavoritedplaceName').text(favoritedName.name); 
$('#FavoritedlocationName').text(favoritedName.location); 
$('#FavoritedtimeofDay').text(favoritedName.timeOfDay); 
$('#FavoriteddayofWeek').text(favoritedName.dayofWeek); 
}); 
+0

如果您在設置之後使用console.log(placesText),您會得到什麼? – K3N

+0

@ Ken-AbdiasSoftware我得到正確的輸出,這是「placesFireside酒吧」,這是「爐邊酒吧」+「地方」的列表項文本() – Aaron

回答

0

我想知道,如果你能動態地的.text()從一個ListItem 加載您在ListView單擊,然後設置爲 關鍵localstorage.getItem()。

是的,你可以設置一個變量,使用直接用於localStorage.getItem()localStorage.setItem()localStorage.removeItem()

var myKey = 'myKey'; 
var myData = 'Data string'; 

localStorage.setItem(myKey, myData); 

alert(localStorage.getItem(myKey)); 

請注意,密鑰區分大小寫,並且空格也會影響密鑰。

檢查您傳遞的項目不包含任何行的飼料,不可見的字符等一個簡單的方法來檢查是console.log(placesText),然後檢查控制檯,如果那場比賽你所期望的:

placesText = "places" + listitemText; 
console.log(placesText); 
console.log(escape(placesText)); 
+0

奇怪,console.log(placesText);返回正確的字符串,這是「placesFireside酒吧」,這是localstorage中正確的鍵值,但它似乎無法解析它在這裏... var favoritedName = JSON.parse(localStorage.getItem(placesText)); – Aaron

+0

@Aaron嘗試在escape()中封裝字符串以查看內容是什麼(您也可以在此處發佈):'console.log(escape(placesText))'。通過這種方式,您可以查看字符串中是否存在一些無法在控制檯中看到的不可打印的字符。 – K3N

+0

有趣......當我做console.log(escape(placesText))時,我得到「placesFireside%20Bar%A0」;我只用console.log(placesText)獲得「placesFireside Bar」; – Aaron

相關問題