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

时间:2012-06-07 22:39:30

标签: javascript jquery html html-select url-parameters

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

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

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

请帮助

3 个答案:

答案 0 :(得分:4)

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

然后使用this函数查看value参数是否已设置并获取它,您可以使用jQuery将其设置为selected

$("#elements option[value='" + result_of_gup + "']").attr("selected","selected") ;

答案 1 :(得分:3)

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

答案 2 :(得分:0)

不使用jQuery执行此操作:

here 创建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];
};