繁体   English   中英

如何使用localstorage和Jquery从多个点击事件中生成一个存储值数组的对象键

[英]How to generate one object key with an array of stored values from multiple on click events using localstorage and Jquery

我是编码新手,我需要使用 localstorage 从输入字段显示过去的搜索值。 我能想到的唯一方法是使用一个对象键和来自点击事件的存储值数组。 问题是,我只能让一个位置显示为一个值,生成的每个值替换最后一个。 我试过 for 循环,但似乎无法让它工作。 这是我到目前为止的代码:

$('.search-city').on('click', function(e){  
    e.preventDefault();
    var textArr = [];
    var text = $(".form-control").val();
    textArr.push(text);
    localStorage.setItem("value1", textArr);  
});

$('.search-city').on('click', function(e){  
  e.preventDefault();
var search = localStorage.getItem("value1")

这会起作用:

$('.search-city').on('click', function(e){  
    e.preventDefault();

    // get the value from local storage
    var localValue = localStorage.getItem('value1');

    // if we had a value, parse it back to an array, if we dont, create an empty array
    var textArr = localValue ? JSON.parse(localValue) : [];

    // get the text from the search input, dont use "form-control"
    // you're likely to have several of those on the page
    // give the element a custom class like "search-input" and use that (id would be even better)
    var text = $('.search-input').val();

    // add the text to the array
    text = trim(text);
    if (text) {
        textArr.push(text);
    }

    // enforce a size limit here by removing the 0 index item if the count has grown too large
    var maxAllowed = 10;
    while (textArr.length > maxAllowed) {
         textArr.shift();
    }

    // localstorage can only hold simple strings so we'll JSON stringify our object and store that 
    localValue = JSON.stringify(textArr);
    localStorage.setItem("value1", localValue);  
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM