问题
I am trying to save selected option in localStorage in HTML, so if you refresh page, the selection stays selected.
I have try this:
HTML:
<select id="edit">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
jQuery:
$(function() {
$('#edit').change(function() {
localStorage.setItem('todoData', this.innerHTML);
});
if(localStorage.getItem('todoData')){
localStorage.getItem('todoData');
}
});
But this seems not to work, any ideas, realy thanks for help...
Live Demo here: http://jsfiddle.net/nwk1g6vp/
回答1:
Store and set the value, not the entire HTML of the select
$(function() {
$('#edit').change(function() {
localStorage.setItem('todoData', this.value);
});
if(localStorage.getItem('todoData')){
$('#edit').val(localStorage.getItem('todoData'));
}
});
FIDDLE
回答2:
Use value
property or .val() function
$('#edit').change(function() {
localStorage.setItem('todoData', this.value); //$(this).val()
});
if (localStorage.getItem('todoData')) {
$('#edit').val(localStorage.getItem('todoData')).trigger('change');
}
Example
来源:https://stackoverflow.com/questions/28265744/how-to-save-select-option-in-localstorage-with-jquery