2012-06-07 126 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]; 
};