我的网页中有一个下拉列表(下面的代码):
<select id="SelectedNumber" >
<option label="choose one"></option>
<option value ="1.aspx">1</option>
<option value ="2.aspx">2</option>
<option value ="3.aspx">3</option>
<option value ="4.aspx">4</option>
</select>
当值更改并重新加载新URL(代码如下:)
时,将调用此函数 $(function(){
// bind change event to select
$('#SelectNumber').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
}
return false;
});
});
现在我的问题是当重新加载页面时我希望它记住选中的选项,而不是下拉列表中的第一个选项。任何建议都会很棒。
由于
答案 0 :(得分:0)
试试这个:
// load last selected URL from local storage
var selectedURL = localStorage.selectedURL;
// add a "selected" attribute to the element if there is a saved state
if(selectedURL)
$("#SelectedNumber option[value='" + selectedURL + "']").attr("selected", "selected");
// bind change event to select
$('#SelectedNumber').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
// save selected url to local storage
localStorage.selectedURL = url;
window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
}
return false;
});
答案 1 :(得分:0)
尝试像这样的jquery cookie插件:
$( document ).ready(init) ;
function init() {
// restore value if present
var cookieValue = $.cookie("comboValue");
if (cookieValue) {
$('#SelectedNumber').val(cookieValue);
}
// bind change event to select
$('#SelectedNumber').bind('change', function () {
var index = $(this).val(); // get selected value
// Store the combo index value into a cookie
$.cookie("comboValue", index);
if (url) {
// window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
// forcing reload in order to simulate navigation to another page.
location.reload();
}
return false;
});
}
还注意到一些&#39; id&#39;如SelectNumber和SelectNumber不匹配,您必须更正代码。