javascript 在页面重新加载时保留下拉选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10940840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retaining dropdown selection on page reload
提问by user765368
I have a select list on a page like this:
我在这样的页面上有一个选择列表:
<select name='elements'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
EDIT: When a user makes a selection, the current page is refreshed, but how do I keep the user's selection visible in the list after the page refresh? In other words, I don't want the list to rollback to its default selected value.
编辑:当用户进行选择时,当前页面会刷新,但如何在页面刷新后让用户的选择在列表中可见?换句话说,我不希望列表回滚到其默认选定值。
Help please
请帮忙
回答by sachleen
Here is a Javascript-only solution.
这是一个仅限 Javascript 的解决方案。
<select name='elements' id='elements' onChange='window.location="yoururl.html?value=" + this.value;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
Then you use thisfunction to see if the value
parameter is set and get it and you can use jQuery to set it as selected
.
然后你使用这个函数查看value
参数是否设置并获取它,你可以使用jQuery将其设置为selected
.
$("#elements option[value='" + result_of_gup + "']").attr("selected","selected") ;
回答by Control Freak
<select name='elements' onChange='window.location="yoururl.php?value=" + this.value;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
回答by BooDooPerson
Doing it without jQuery:
在没有 jQuery 的情况下执行此操作:
Create window.location.getParameter()
function (see herefrom Anatoly Mironov) then:
创建window.location.getParameter()
函数(从Anatoly Mironov看这里)然后:
<select name='elements' id='elements' onChange='window.location="yoururl.html?elements=" + this.selectedIndex;'>
<option value='water'>Water</option>
<option value='fire'>Fire</option>
<option value='air'>Air</option>
</select>
<script type="text/javascript">
els = document.getElementById('elements');
selIndex = window.location.getParameter('elements') || 0;
els[selIndex].selected = true;?
</script>
For ease of reference, I reproduce Anatoly's excellent .getParameter
function below:
为了方便参考,我.getParameter
在下面重现了 Anatoly 的优秀功能:
window.location.getParameter = function(key) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[key];
};