代码之家  ›  专栏  ›  技术社区  ›  Dan

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

  •  0
  • Dan  · 技术社区  · 8 年前

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

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

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

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

    返回到同一页时,会显示结果,因为我将其放置在原始函数之外:

    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>
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   xuhaib    8 年前

    您可以替换

    var weather = [];
    

    具有

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

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