记住带有jquery的选择菜单选项

时间:2012-05-30 02:32:53

标签: jquery

我有4个动态相关的选择菜单。菜单对应州,县,地区,社区。动态依赖是通过jQuery脚本实现的。我想要完成的是让菜单记住用户为每个菜单选择的最后一个选项。所以我想如果我能抓住那些可以解决问题的url参数。 所以我用这种方式修改了脚本....

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

1 个答案:

答案 0 :(得分:1)

我不知道什么是“county_id”,但我想是另一个菜单,所以可能更好:

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
}