Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-记住所选选项_Javascript_Sorting_Select - Fatal编程技术网

Javascript-记住所选选项

Javascript-记住所选选项,javascript,sorting,select,Javascript,Sorting,Select,我有一个通过javascript注入创建的网页,我的一个网页有一个下拉列表,如下所示: html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value); display(document.getElementById(\"searchQuery\").

我有一个通过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>";  
html+=“\n”;
html+=“\n”;
html+=“最小的第一个\n”;
html+=“最大的第一个\n”;
html+=“A-Z\n”;
html+=“Z-A\n”;
html+=“”;
下拉列表通过将所选选项传递给开关功能来过滤页面上显示的信息,另一个功能将重新加载此信息。但是,当JavaScript页面再次加载时,它将从空白选项开始。p> 有人知道有什么好方法可以记住最后选择的排序吗?例如,如果我排序“最小的第一”,然后页面刷新,该框将显示“最小的第一”,作为填补空白。我知道有一个“optionselected”属性,但我需要它是动态的。我觉得这是一件微不足道的事情,但我似乎不能把我的手指放在上面


提前谢谢

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

我使用

这里有一篇文章解释了它们的工作原理,以及读取、写入和删除cookie的函数

使用这些函数,您将获得所选值并写入cookie,以如下方式保存值:

var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);
var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;
然后读取cookie以检索值,并在
选择
框中选择
选项
,如下所示:

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

您有没有研究过
localStorage
sessionStorage