Javascript - 记住选定的选项 [英] Javascript - Remember Selected Option

查看:123
本文介绍了Javascript - 记住选定的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a webpage thats created by javascript injections and one of my pages has a dropdown shown below:

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页面再次加载时,它会以空白选项开始。

The dropdown filters the information displayed on the page by passing the selected option to a switch function and another function reloads this information. However, when the javascript page loads again, it starts off with the blank option.

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

Does anyone know of a good way to remember the last sort selected? For example, if I sort with "Smallest First" and then the page refreshes, the box will show "Smallest First" as apposed to the blank. I know there is an "option selected" attribute, but I need it to be dynamic. I feel like it is something trivial, yet I can't seem to put my finger on it.

提前致谢!

推荐答案

这是一篇关于 Cookies的文章在JavaScript中 ,其中包含有关其工作原理的说明,以及读取,写入和删除Cookie的功能。

Here's an article on Cookies in JavaScript which contains an explanation of how they work, along with functions to read, write and delete cookies.

使用这些功能d获取所选值并编写cookie 以保存这样的值:

Using those functions you'd get the selected value and write the cookie to save the value like this:

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

然后读取cookie 以检索值并选择选项选择框中,如下所示:

then read the cookie to retrieve the value and select the option in the select box, like this:

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

这篇关于Javascript - 记住选定的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆