2012-06-07 74 views
0

我有这样一个页面上选择列表:保留下拉选项

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

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

请帮助

+1

是否有任何理由需要整页刷新?为什么不简单地显示/隐藏/填充异步调用...? – balexandre

+0

我想翻译整个页面的内容到另一种语言,所以是的,我想整个页面刷新 – user765368

回答

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

那么'保持用户的选择在列表中可见? – user765368

+0

只要你用查询字符串加载了新的页面,就必须在'yoururl.php?value = fire'页面上担心,只需使用该值来相应地呈现你的新页面。要预先选择一个项目一个列表只是执行''。此外,你几乎没有发布任何代码,所以很难说你真的需要完成什么。 –

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") ; 
0

又未jQuery的:

创建window.location.getParameter()功能(请参阅从Anatoly Mironovhere),则:

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

为便于参照,我下重现阿纳托利的优秀.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]; 
};