如何在选择选项后立即从选择菜单中将值保存到本地存储?它不起作用

How to save a value to localstorage from a select menu as soon as u select the option? It is not working

本文关键字:选择 保存 存储 不起作用 选项 菜单      更新时间:2023-09-26

我有以下内容,但我不断得到null的返回值,而不是我尝试存储的值。这是我的代码:

function mySelectValue() {
    // Add an event listener for the value
    document.getElementById('mySelectValue').addEventListener('change', function() {
      // Get the value of the name field.
      var mySelectValue = document.getElementById('mySelectValue').value;
      // Save the name in localStorage.
      localStorage.setItem('mySelectValue', mySelectValue);
    });
}

但是,当我尝试检索值时,它null我认为这意味着该值未存储。

基本上,一旦我选择该选项(尚未提交),我就希望将其存储在本地存储中。此外,我希望如果我更改我的选择,它会覆盖该值。

如果你允许使用 jQuery,试试这个:

$(document).ready(function(){
    $('#mySelectValue').change(function(){
         localStorage.setItem('mySelectValue', $(this).val());
    });
});

你在其他地方有问题,这段代码有效,你可以在这里检查它: 小提琴