javascript-HTML中带有localStorage变量的搜索历史记录

我正在使用PhoneGap创建一个jQuery移动应用程序,并且我想列出旧的搜索结果(由表单输入并存储在localStorage中).

有两个不同的问题要解决:

1)我会将结果存储在localStorage数组中,如果用户第二次搜索,则应将结果添加到旧结果之后的数组中,例如:city [0] =“ New York”,city [1] = “巴黎” …如何保存和读取数组中的字符串,例如:

localStorage.setItem('city[i]', $('#city').val()); 
or
localStorage.getItem('city[i]');

2)现在我想显示搜索历史.我已经尝试过了,但是:

>我不知道如何在html列表中显示localStorage数组或变量,并且…
>如果localStorage中没有变量,则不会加载网站.

<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>

解决方法:

<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来缩短代码.

上一篇:java-如何在android phonegap应用程序中获取webview URL?


下一篇:day07-数据类型及标识符