用户可以搜索位置。然后出于不同原因将其存储在本地和会话存储中。他们使用这个html进行搜索:
<input type="text" name="city" class="city" placeholder="City Name">
<button class="submitLocation">Set location</button></br>
结果显示在搜索框下方。当他们搜索其他名称时,这些名称也会作为结果添加到li元素中,使用for循环。
用户可以从一个页面到另一个页面,这些详细信息按预期存储。
返回同一页面后,会显示结果,因为我将其置于原始功能之外:
document.getElementById("historyList2").innerHTML = JSON.parse(localStorage.getItem("weather"));
(我希望在返回页面时在列表中显示结果,就像在函数中一样)。但是,可能会解决该问题的方法是解决在返回页面时再次搜索时出现的主要问题。发生这种情况时,数组将返回空,因为var weather = [];
。
var weather = [];
var weatherLength;
var text;
var i;
function showCurrent(currentWeather) {
// for the for loop
weather.push( currentWeather.name );
if (typeof(Storage) !== "undefined") {
// Store
//saves name/s in local storage (for histoy list)
localStorage.setItem("weather", JSON.stringify( weather ) );
//saves name in session storage for current use
sessionStorage.setItem("name", currentWeather.name);
// Retrieve
// Retrieves name from session storage
document.getElementById("name").innerHTML = sessionStorage.getItem("name");
// bring back list of previous locations
weatherLength = weather.length;
text = "<ul>";
for (i = 0; i < weatherLength; i++) {
text += "<li class='city'>" + weather[i] + "</li>";
}
text += "</ul>";
//outputs result as list
document.getElementById("historyList").innerHTML = text;
//outputs result as string
var storedLocations = document.getElementById("historyList2").innerHTML = JSON.parse(localStorage.getItem("weather"));
}
else {
document.getElementById("error").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
//need to put here to display results on return to page
document.getElementById("historyList2").innerHTML = JSON.parse(localStorage.getItem("weather"));
输出:
document.getElementById("historyList").innerHTML = text;
给出了这个:
<div id="historyList">
<ul>
<li class="city">London</li>
<li class="city">Manchester</li>
<li class="city">Glasgow</li>
</ul>
</div>
document.getElementById("historyList2").innerHTML = JSON.parse(localStorage.getItem("weather"));
给出了这个:
<div id="historyList2">London,Manchester,Glasgow</div>
答案 0 :(得分:1)
您可以替换
var weather = [];
与
var weather = localStorage.getItem("weather") === null ? [] : JSON.parse(localStorage.getItem("weather"));
曾要求样本输出能够帮助更具体的代码。但希望这会有所帮助。