我正在使用PhoneGap创建一个jQuery移动应用程序,我想列出旧的搜索结果(由表单输入并存储在localStorage中)。
要解决两个不同的问题:
1)我将结果存储在localStorage数组中,如果用户第二次搜索,结果应该在旧结果之后添加到数组中:city [0] =“New York”,city [ 1] =“巴黎”...如何保存并读取数组中的字符串,例如:
localStorage.setItem('city[i]', $('#city').val());
or
localStorage.getItem('city[i]');
2)现在我想显示搜索历史。我试过这个,但是:
<div id="lastResults"></div>
<script>
var history = "";
if (localStorage.getItem("history") !== "") {
var history = localStorage.getItem("history");
}
if ( history !== "") {
$("#lastResults").html(
"<b>Last Results:</b>" +
"<ul data-role=\"listview\" data-inset=\"true\" >" +
"<li><a href=\"#test\"> " + document.write(history) + " </a></li>" +
"</ul>"
);
}
</script>
答案 0 :(得分:2)
<div id="lastResults"></div>
<script type="text/javascript">
//To Check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
var oldhistoryarray = historyTmp.split('|');
$('#lastResults').empty();
for(var i =0; i<oldhistoryarray.length; i++)
{
$('#lastResults').append('<p>'+oldhistoryarray[i]+'</p>');
}
}
//Storing New result in previous History localstorage
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
historyTmp += '|Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
else
{
var historyTmp = 'Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
</script>
注意我使用jquery进行代码缩短。
答案 1 :(得分:2)
LocalStorage存储键值对,其中键和值都是字符串。解决此问题的一种方法是使用JSON对象来存储数据,并使用JSON.stringify和JSON.parse将数据从对象更改为字符串并返回。
实施例
var historyObj = { city: [] };
function onLoad() {
if(localStorage.getItem('history') != '') {
historyObj = JSON.parse(localStorage.getItem('history'));
}
}
function addHistory(dataToSave) {
historyObj.city.push(dataToSave);
localStorage.setItem('history',JSON.stringify(historyObj));
}