我有一个问题,本地存储保存了第一个下拉菜单选项,但没有保存第二个和第三个菜单。应该在HTML和JS中编辑或添加多个内容。
var init = function (){
//an ugly warning to users without localStorage support
if(!window.localStorage){
$('body').prepend('Sorry, you browser does not support local storage');
return false;
}
var sel = $('select'),
but = $('button');
var clearSelected = function(){
sel.find(':selected').prop('selected', false);
}
if(localStorage.getItem('pref')){
var pref = localStorage.getItem('pref');
clearSelected();
//set the selected state to true on the option localStorage remembers
sel.find('#' + pref).prop('selected', true);
}
var setPreference = function(){
//remember the ID of the option the user selected
localStorage.setItem('pref', sel.find(':selected').attr('id'));
};
var reset = function(){
clearSelected();
localStorage.setItem('pref', undefined);
}
sel.on('change', setPreference);
but.on('click', reset);
};
$(document).ready(init);
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="2.js"></script>
</head>
<select>
<option selected></option>
<option id="opt1">1</option>
<option id="opt2">2</option>
<option id="opt3">3</option>
<option id="opt4">4</option>
</select>
<br></br>
<select>
<option selected></option>
<option id="opt5">5</option>
<option id="opt6">6</option>
<option id="opt7">7</option>
<option id="opt8">8</option>
</select>
答案 0 :(得分:0)
var sel = $('select'),
选择两个下拉列表。
将ID添加到下拉列表
<select id="first">
将setPreference
更改为此
var setPreference = function () {
//remember the ID of the option the user selected
localStorage.setItem('pref', this.value);
};
,并相应地调整本地存储检索逻辑。
答案 1 :(得分:0)
我进行了更改,但是现在它们都无法保存。我为自己的知识水平而道歉,但这是我的第一次,只是需要工作而已。
var init = function (){
//an ugly warning to users without localStorage support
if(!window.localStorage){
$('body').prepend('Sorry, you browser does not support local storage');
return false;
}
var sel = $('select'),
but = $('button');
var clearSelected = function(){
sel.find(':selected').prop('selected', false);
}
if(localStorage.getItem('pref')){
var pref = localStorage.getItem('pref');
clearSelected();
//set the selected state to true on the option localStorage remembers
sel.find('#' + pref).prop('selected', true);
}
var setPreference = function () {
//remember the ID of the option the user selected
localStorage.setItem('pref', this.value);
};
var reset = function(){
clearSelected();
localStorage.setItem('pref', undefined);
}
sel.on('change', setPreference);
but.on('click', reset);
};
$(document).ready(init);
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="2.js"></script>
</head>
<select id="first">
<option id="opt1">1</option>
<option id="opt2">2</option>
<option id="opt3">3</option>
<option id="opt4">4</option>
</select>
<br></br>
<select id="second">
<option id="opt5">5</option>
<option id="opt6">6</option>
<option id="opt7">7</option>
<option id="opt8">8</option>
</select>
<br></br>