在页面重新加载时保留下拉选择

Retaining dropdown selection on page reload

本文关键字:保留 选择 加载 新加载      更新时间:2023-09-26

我在这样的页面上有一个选择列表:

<select name='elements'>
    <option value='water'>Water</option>
    <option value='fire'>Fire</option>
    <option value='air'>Air</option>
</select>

编辑:当用户进行选择时,当前页面将刷新,但是如何在页面刷新后使用户的选择在列表中可见?换句话说,我不希望列表回滚到其默认的选定值。

请帮忙

这是一个仅限 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>

然后你用这个函数查看value参数是否设置并获取它,你可以用jQuery把它设置为selected

$("#elements option[value='" + result_of_gup + "']").attr("selected","selected") ;
 <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>

在没有 jQuery 的情况下执行此操作:

创建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>

为了便于参考,我在下面重现了Anatoly的出色.getParameter功能:

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];
};