多次存储相同的本地存储项目

时间:2018-04-13 23:50:31

标签: javascript jquery local-storage

我可以输入文本并搜索数据,然后存储该数据,在本例中为名称。

localStorage.setItem("name", currentWeather.name);

使用for循环(在同一页面上),我可以进行多次搜索,页面上会显示每次搜索的名称数据。

    for (var i = 0; i < localStorage.length; i++){
    $("#record").append(localStorage.getItem(localStorage.key(i)));
    }

我现在希望能够存储每个名称,因此当我返回该页面时,它仍会显示所有名称。目前,本地存储只能存储最新名称。我猜我需要创建一个数组,我可以存储每个搜索词,但不知道如何去做。我看到有人建议可以这样做,而其他人只是说这是不可能的。

$(document).ready(function(){

    $('#submitLocation').click(function(){

        //get value from input field
        var city = $("#city").val();

        //check not empty
        if (city !== ''){

            $.ajax({
                url: "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + "&APPID",
                type: "GET",
                dataType: "jsonp",
                success: function(weatherData){
                    var currentWeather = showCurrent(weatherData);
                }
            });

        }else{
            $('#error').html('Field cannot be empty');
        }
    });
});


function showCurrent(currentWeather) {
console.log(currentWeather);
console.log(currentWeather.name);

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

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

        //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");

        // Retrieves name from local storage for history list
        document.getElementById("name").innerHTML = localStorage.getItem("name");

        // Outputs all locations searched
        for (var i = 0; i < localStorage.length; i++){
        $("#record").append(localStorage.getItem(localStorage.key(i)));
        }

}


    else {
        document.getElementById("error").innerHTML = "Sorry, your browser does not support Web Storage...";
    }

2 个答案:

答案 0 :(得分:1)

localStorage仅存储字符串,因此要存储使用JSON.stringify的数组或对象。

var names = [ 'Philbo', 'Nipwip', 'Henk' ];
localStorage.setItem( 'names', JSON.stringify( names ) );

然后使用JSON.parse检索它。

var names = JSON.parse( localStorage.getItem('names') );

让我们变得愚蠢,并在一个单行中添加一个新名称:

localStorage.setItem( 'names',
    JSON.stringify(
        JSON.parse(
            localStorage.getItem( 'names' ) || '[]'
        ).concat([ 'Billiam' ])
    )
)

对于你的问题:

var weather = [];
function showCurrent(currentWeather) {

    weather.push( currentWeather.name );

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

        localStorage.setItem("weather", JSON.stringify( weather ) );

        ...

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

答案 1 :(得分:0)

乍一看,好像你一遍又一遍地设置相同的密钥,所以你只需要在localStorage中有一个键值对(&#34; name&#34;)。即使您将currentWeather.name值存储在数组中,您仍然最终会重新分配相同的&#34; name&#34;钥匙一遍又一遍。

相反,您可以使指定的键动态化,例如

localStorage.setItem(currentWeather.id, currentWeather.name);

或者那种效果。我不知道你的currentWeather对象会有什么属性。您甚至可以简单地将名称值分配给setItem的两个参数。

相关问题