如何在刷新页面后使用文档cookie功能使浏览器记住用户选择的下拉列表?在更改选择时,浏览器会使用添加到URL的额外参数刷新自身,但会恢复默认下拉选项而不是用户选择的选项..
<select id="MyDropDown" onchange="document.cookie=this.selectedIndex; window.open(this.options[this.selectedIndex].value,'_top')">
<option value="http://mysite.com/default1.aspx?alpha=A">A</option>
<option value="http://mysite.com/default1.aspx?alpha=B">B</option>
<option value="http://mysite.com/default1.aspx?alpha=C">C</option>
</select>
答案 0 :(得分:1)
bebonham的答案有效,但下拉列表中最多只有9个选项。我调整它以使其适用于更长的下拉列表。
<html>
<body>
<select id="MyDropDown" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;'; window.open(this.options[this.selectedIndex].value,'_top')">
<option value="http://example.com/default1.aspx?alpha=A">A</option>
<option value="http://example.com/default1.aspx?alpha=B">B</option>
<option value="http://example.com/default1.aspx?alpha=C">C</option>
</select>
<SCRIPT>
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
window.onload = function () { document.getElementById("MyDropDown").selectedIndex = readCookie("myDDIdx"); }
</SCRIPT>
</body>
答案 1 :(得分:0)
要保存选择,请使用:
document.cookie='myselection='+this.selectedIndex;
这将使您的选择在名为myselection
编写一个函数来读取cookie并设置保存的值并在文档的onload上调用它。即。
function setSavedValue() {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" myselection=");
if (ind==-1) ind=theCookie.indexOf(";myselection=");
if (ind==-1) return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+'myselection'.length+2,ind1));
}
并在你的onload上调用它:
<body onload="setSavedValue()">
答案 2 :(得分:0)
使用jQuery(或普通的旧JavaScript)插入新的select元素。使用普通的提交按钮在表单中构建它,这样如果用户禁用了JavaScript,您只需在服务器端重建HTML。
答案 3 :(得分:0)
<html>
<body>
<select id="MyDropDown" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;'; window.open(this.options[this.selectedIndex].value,'_top')">
<option value="http://mysite.com/default1.aspx?alpha=A">A</option>
<option value="http://mysite.com/default1.aspx?alpha=B">B</option>
<option value="http://mysite.com/default1.aspx?alpha=C">C</option>
</select>
<script>
var sidx = document.cookie.indexOf("myDDIdx");
if(sidx != -1)
window.onload = function () { document.getElementById("MyDropDown").selectedIndex = document.cookie.substr(sidx + 8,1); }
</script>
</body>