2012-05-30 42 views
0

我有4個動態相關的選擇菜單。菜單對應於州,縣,地區,鄰里。動態依賴通過jQuery腳本實現。我想要完成的是讓菜單記住用戶爲每個菜單選擇的最後一個選項。所以我認爲,如果我能抓住可以做到這一點的url參數。 所以我用這種方式修改了劇本....記住與jquery的選擇菜單選項

getCounty: function (results) { 
    if(!results) return; 
    var allCounties = $("<option value=\"All\">All Counties </option>"); 
    counties.html(results); 
    counties.prepend(allCounties); 
    var w = $.query.get("county_id"); 
    if(w) { 
     counties.val(w).attr('selected', true); 
    } else { 
     counties.val("All").attr('selected', true); 
    } 

是在$.query.get功能是否正確?我的代碼還有什麼不對嗎?我不得不承認,我不是一個jQuery的專家...代碼工作得很好,如果我鍵入

counties.val(3).attr('selected',true) 

選擇菜單中的第三個選項被選中。

我用

function getUrlVars() { 
    var vars = {}; 
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { 
    vars[key] = value; 
    }); 
    return vars; 
} 

並解決問題

var county = getUrlVars()["county_id"]; 

    if (county)  
    counties.val(county).attr('selected',true); 
    else 
     counties.val("All").attr('selected',true); 
+0

爲什麼你使用'attr('selected',true)'作爲? – zerkms

回答

1

我不知道什麼是 「county_id」,但我supose是其他菜單後,也許更好:

getCounty: function (results) { 
if(!results) return; 
var allCounties = $("<option value=\"All\">All Counties </option>"); 
counties.html(results); 
counties.append(allCounties); ///The all option first 
var w = $('#county_id :selected').val(); ///w is the value of option selected of other combo 
counties.find('option[value='+w+']').attr('selected', 'selected'); ///this find a option with value W, if exist mark like selected 
} 
+1

我認爲,因爲我使用一個.get函數,很顯然,我在談論一個url參數(查詢執行最後一次用戶搜索的東西)。無論如何,我發現了一個傳統的JavaScript函數,它可以獲取url參數並解決問題。非常感謝您花時間回答我。隨着您的回答,我豐富了我的jquery知識! – user926652