2012-01-05 55 views
0

如何使用文件cookie功能使浏览器在页面刷新后记住用户选择的下拉菜单?在选择的变化,浏览器刷新本身添加到URL额外的参数,但恢复默认的下拉列表选项,而不是用户选择的一个..文件Cookie记住下拉选择

<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

难道你没有[问这个问题](http://stackoverflow.com/questions/8745328/cookie-to-remember-dropdown-selection)? – 2012-01-05 17:56:07

回答

0

为了节省挑选,使用此:

document.cookie='myselection='+this.selectedIndex; 

这会使您的选择在名为myselection的Cookie上可用

编写函数以读取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()"> 
0

使用jQuery(或传统的JavaScript)来插入新的选择元素。使用正常的提交按钮在表单中构建它,以便如果用户禁用JavaScript,则只需在服务器端重新构建HTML。

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> 

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>