Javascript - 记住选定的选项

时间:2011-05-13 18:32:16

标签: javascript sorting select

我有一个由javascript注入创建的网页,其中一个网页的下拉列表如下所示:

html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value);     display(document.getElementById(\"searchQuery\").value);return false;'>\n";  
  html +="<option></option>\n";  
  html +="<option value='4'>Smallest First</option>\n";  
  html +="<option value='5'>Largest First</option>\n";  
  html +="<option value='6'>A-Z</option>\n";  
  html +="<option value='7'>Z-A</option>\n";  
  html +="</select>";  

下拉列表通过将所选选项传递给切换功能来过滤页面上显示的信息,另一个功能会重新加载此信息。但是,当javascript页面再次加载时,它会以空白选项开始。

有没有人知道记住最后一种选择的好方法?例如,如果我使用“最小的第一个”进行排序然后页面刷新,则该框将显示与空白相关的“最小的第一个”。我知道有一个“选择选项”属性,但我需要它是动态的。我觉得这是微不足道的,但我似乎无法将手指放在上面。

提前致谢!

2 个答案:

答案 0 :(得分:4)

这是一篇关于Cookies in JavaScript的文章,其中包含对它们如何工作的解释,以及读取,写入和删除cookie的功能。

使用这些功能,您将获得所选值,编写Cookie 以保存值,如下所示:

var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);

然后阅读Cookie 以检索该值并在option框中选择select,如下所示:

var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;

答案 1 :(得分:1)

您需要使用Cookie。或者服务器端的一些会话变量来保存所选的值。

我使用this jQuery cookie plugin

相关问题