0

我有 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);
4

1 回答 1

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
}
于 2012-05-30T03:11:58.657 回答