How to use LocalStorage on last HTML select value

后端 未结 2 1839
孤城傲影
孤城傲影 2020-12-19 18:19

How can I set/retrieve the last selected value of a select drop-down with JavaScript? I\'m trying to create an onchange function on a select drop-down that that sets the sel

2条回答
  •  我在风中等你
    2020-12-19 18:51

    You have at least two problems in your code.

    1. The first one is an scope problem: The lastSelected variable is local defined in your function. You must define as global variable.

    2. The second one is that the first parameter of setItem & getItem methods should be a String

    So your corrected code looks like:

    var lastSelected;
    
    var select = document.querySelector(".testSelect");
    var selectOption = select.options[select.selectedIndex];
    var getLast = localStorage.getItem('select', lastSelected);
    selectOption = getLast;
    
    
    select.onchange = function () {
       lastSelected = select.options[select.selectedIndex].value;
       localStorage.setItem('select', lastSelected);
     };
    

提交回复
热议问题