Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

javascript - How to use LocalStorage on last HTML select value

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 selected option, and then on each page-load, that valued is loaded.

Here is the HTML

<select class="testSelect">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
    <option value="test2">test3</option>
    <option value="test2">test4</option>
</select>

I'm having a little trouble with the JavaSCript though.

var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem(select, lastSelected);
selectOption = getLast;


select.onchange = function () {
   var lastSelected = select.options[select.selectedIndex].value;
   localStorage.setItem(select, lastSelected);
 }

and here's a fiddle http://jsfiddle.net/5yJNL/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The values in your HTML were wrong

<select class="testSelect">
    <option value="test1">test1</option>
    <option value="test2">test2</option>
    <option value="test3">test3</option>
    <option value="test4">test4</option>
</select>    

Javascript

var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');

if(lastSelected) {
    select.value = lastSelected; 
}

select.onchange = function () {
   lastSelected = select.options[select.selectedIndex].value;
   console.log(lastSelected);
   localStorage.setItem('select', lastSelected);
}

http://jsfiddle.net/2MPPz/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...