即使重新打开应用程序后如何将上次选择的值保留在下拉列表中

时间:2018-07-19 13:42:17

标签: javascript jquery memory

dropdown = '';
dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';
$('.tab-setup select[name=languageSelect]').html(dropdown);

html

<select class="dropdown" name="languageSelect" id="selectlanguage"></select>

datavariable.js

var CONFIGURATOR = {
    'ChineseLanguage': 'zh',
    'EnglishLanguage': 'en'
};

即使重新打开应用程序后,下拉列表中如何保持最后一次选择的选项仍然出现

1 个答案:

答案 0 :(得分:0)

您可以使用 localStorage API存储该值,即使关闭应用程序,该值也将保留。

var dropdown = '',
    $select = $('.tab-setup select[name=languageSelect]'),
    storedValue = localStorage.getItem('languageSelectValue');

dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';

$select.html(dropdown);

//Set the initial value if any
if (storedValue) {
    $select.val(storedValue);
}

//Bind a listener to store the selected value in localStorage
$select.on('change', function () {
    localStorage.setItem('languageSelectValue', $(this).val());
});