javascript
  • sorting
  • select
  • 2011-05-13 104 views 2 likes 
    2

    我有JavaScript的注射和我的一個網頁創建了一個網頁,這就是具有以下所示的下拉:使用Javascript - 記住所選選項

    html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value);  display(document.getElementById(\"searchQuery\").value);return false;'>\n"; 
        html +="<option></option>\n"; 
        html +="<option value='4'>Smallest First</option>\n"; 
        html +="<option value='5'>Largest First</option>\n"; 
        html +="<option value='6'>A-Z</option>\n"; 
        html +="<option value='7'>Z-A</option>\n"; 
        html +="</select>"; 
    

    下拉通過將選定的選項過濾網頁上顯示的信息一個開關功能和另一個功能重新加載這個信息。但是,當再次加載javascript頁面時,它將以空白選項開始。

    有沒有人知道記住最後一種選擇的好方法?例如,如果我按照「最小的優先」排序,然後頁面刷新,那麼該框會顯示「最小的優先」。我知道有一個「選項選擇」屬性,但我需要它是動態的。我覺得這是微不足道的,但我似乎無法把它指向它。

    在此先感謝!

    +0

    你看過'localStorage'還是'sessionStorage'呢? – Thai 2011-05-13 18:43:35

    回答

    4

    這裏有Cookies in JavaScript其中包含它們是如何工作的解釋,與功能一起讀,寫和刪除cookies的文章。

    使用這些功能,你會得到選擇的值和寫的cookie保存這樣的值:

    var select = document.getElementById("Sort"); 
    var selectedItem = select.options[select.selectedIndex].value; 
    createCookie("selectedItem",selectedItem); 
    

    然後讀取cookie檢索值並選擇了optionselect框,如下所示:

    var selectedItem = readCookie("selectedItem"); 
    var select = document.getElementById("Sort"); 
    select.value = selectedItem; 
    
    1

    您需要使用Cookie。或服務器端的一些會話變量來保存所選的值。

    我用this jQuery cookie plugin

    相關問題