在返回创建数组的页面时执行操作时数组清空

Array empties when action taken on returning to the page the array was created

用户可以搜索位置。然后出于不同的原因将其存储在本地和会话存储中。他们使用 html:

进行搜索
<input type="text" name="city" class="city" placeholder="City Name">
<button class="submitLocation">Set location</button></br>

结果显示在搜索框下方。当他们搜索其他名称时,这些名称也会使用 for 循环作为结果添加到 li 元素中。

用户可以从一个页面转到另一个页面,这些详细信息将按预期存储。

在 return 转到同一页面时,显示了结果,因为我将其放置在原始函数之外:

document.getElementById("historyList2").innerHTML = JSON.parse(localStorage.getItem("weather"));

(我更喜欢在 return 上的列表中将结果显示到页面,就像我在函数中所做的那样)。但是,可能解决该问题的是解决当您再次搜索 return 页面时出现的主要问题。发生这种情况时,数组 returns 会变空,因为 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>

你可以替换

var weather = [];

var weather = localStorage.getItem("weather") === null ? [] : JSON.parse(localStorage.getItem("weather"));

曾要求提供示例输出以帮助编写更具体的代码。但希望这会有所帮助。