restore dropdown selection after refresh local storage

前端 未结 3 1593
眼角桃花
眼角桃花 2021-01-03 12:42

I am trying to save an options tag value to local storage. After saving its value to local storage I would like to be able to set the options tag to the option the user sele

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 13:20

    Because your option values are integers, in this case, I would check against the value of the option, not the textual contents of the option element.

    Here's a solution that works if you have incremental numerical option values, starting from zero:

    DEMO

    HTML:

    
    

    And your JS would be:

    document.getElementById("fruit").onchange = function() {
        localStorage.setItem('fruit', document.getElementById("fruit").value);
    }
    
    if (localStorage.getItem('fruit')) {
        document.getElementById("fruit").options[localStorage.getItem('fruit')].selected = true;
    }​
    

提交回复
热议问题