用于多个选择选项下拉菜单的本地存储 [英] local storage for multiple select option dropdowns

查看:133
本文介绍了用于多个选择选项下拉菜单的本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个选择选项下拉菜单,并且希望在选择用户后使用本地存储来保存他们的选择.这是HTML的示例:

I have multiple select option dropdowns and want to use local storage to save the user's choices once they have been selected. This is an example of the HTML:

<div class="sel_container">
    <select onchange="saveChoice()" id="select_color" class="test">
        <option value="">Choose color</option>
        <option value="red">red</option>
        <option value="blue">blue</option>
        <option value="green">green</option>
    </select>
    <select id="select_type" class="test" onchange="saveChoice()">
        <option value="">Choose size</option>
        <option value="small">small</option>
        <option value="medium">medium</option>
    </select> 
</div>

我从发现的另一篇文章中使用了此代码,它可以保存其中的一个选择:

I used this code from another post I found and it works to save one of the selections:

$(function() {
    $('#select_color').change(function() {
        localStorage.setItem('todoData', this.value);
    });
    if(localStorage.getItem('todoData')){
        $('#select_color').val(localStorage.getItem('todoData'));
    }
});

我是javascript的新手,在阅读了一些内容之后,似乎需要进行JSON字符串化,但是我对此语法确实感到困惑.我尝试使用此方法,但它不起作用:

I am new with javascript and after doing some reading it seems like I need to do a JSON stringify, but I am really confused about the syntax of this. I tried using this and it does not work:

var obj = {
    "#select_color": this.value,
    "#select_type": this.value
}
var stringifyObj = JSON.stringify(obj);

任何帮助,我们将不胜感激!谢谢!

Any help with this is much appreciated! Thanks!

推荐答案

您无需为此专门使用对象或JSON.您可以做的是通过提高代码的通用性来改进代码,使其适用于select的任何实例.

You don't need to use an object nor JSON for this specifically. What you could do is improve your code by making it more generic so that it works for any instance of a select.

您已经给了他们两个.test类,因此可以选择它们.然后,您可以在以selectid为键的localstorage中设置值,可以在页面加载时检索该值.试试这个;

You have given them both the .test class, so you can select by that. You can then set the value in localstorage keyed by the id of the select, which can be retrieved on page load. Try this;

$('.test').change(function() {
    localStorage.setItem(this.id, this.value);
}).val(function() {
    return localStorage.getItem(this.id)
});

工作示例

这篇关于用于多个选择选项下拉菜单的本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆