Javascript 在jQuery中追加本地存储项

Javascript 在jQuery中追加本地存储项,javascript,jquery,local-storage,Javascript,Jquery,Local Storage,我正在尝试显示以前搜索的位置的列表。我在整个网站上使用会话存储,本地存储专门用于搜索历史记录 目前 if (typeof(Storage) !== "undefined") { //saves name in local storage (for histoy list) localStorage.setItem("name", currentWeather.name); //saves name in session storage - could be other

我正在尝试显示以前搜索的位置的列表。我在整个网站上使用会话存储,本地存储专门用于搜索历史记录

目前

if (typeof(Storage) !== "undefined") {

    //saves name in local storage (for histoy list)
    localStorage.setItem("name", currentWeather.name);

    //saves name in session storage - could be other things
    sessionStorage.setItem("name", currentWeather.name);

    // Retrieve session storage name to display back current location on search page
    document.getElementById("name").innerHTML = sessionStorage.getItem("name");

    // History
    var previous = {
        location : $("#name").val(), 
    }

    var record = JSON.stringify(previous.location);
    localStorage.setItem(previous.location, record); 

    for (var i = 0; i < localStorage.length; i++){
    $("#record").append(localStorage.getItem(localStorage.key(i)));
    }
if(类型(存储)!=“未定义”){
//将名称保存在本地存储器中(用于历史记录列表)
localStorage.setItem(“name”,currentWeather.name);
//将名称保存在会话存储中-可能是其他内容
sessionStorage.setItem(“name”,currentWeather.name);
//检索会话存储名称以在搜索页面上显示回当前位置
document.getElementById(“名称”).innerHTML=sessionStorage.getItem(“名称”);
//历史
前一个变量={
位置:$(“#名称”).val(),
}
var record=JSON.stringify(previous.location);
localStorage.setItem(previous.location,record);
for(var i=0;i
html:

位置设置为:

记录:

因此,在尝试放入列表之前,我只想让位置简单地输出。目前它是这样出现的:

“曼彻斯特”爱丁堡


在chrome应用程序选项卡上,会话存储区显示一个名称键,最新的名称出现在那里。它还显示一个值为
的空白键,我不明白为什么或如何解决这个问题。

很可能是因为
$(“#name”).val()
脚本中的一行代码。因为您试图获取span标记的值,该值在所使用的元素上为空或不可用(

之后,您将使用它作为键来设置本地存储中的数据。因为这是一个空的,所以您会看到
。只需将
$(“#name”).val()
替换为
$(“#name”).html()
,或者以任何方式访问要保存在本地存储中的值即可

希望有帮助

感谢

,因为
$(“#name”).val()
。这将为您提供
null
或空字符串,您在这里使用它,即
localStorage.setItem(previous.location,record);
来设置键
<p>Location set to: <span id="name"></span></p>


<p>Record:</p>
<a id="record"></a>