使用jquery调用select菜单选项

使用jquery调用select菜单选项,jquery,Jquery,我有4个动态相关的选择菜单。菜单对应于州、县、地区、社区。动态依赖性是通过jQuery脚本实现的。我想实现的是让菜单记住用户为每个菜单选择的最后一个选项。所以我想,如果我能抓取url参数,就可以做到这一点。 所以我用这种方式修改了脚本 getCounty: function (results) { if(!results) return; var allCounties = $("<option value=\"All\">All Counties </opti

我有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);
    }
选择菜单的第三个选项被选中

我用计算机解决了这个问题

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);
我不知道什么是“县城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
}
getCounty:函数(结果){
如果(!results)返回;
var AllCountries=$(“所有县”);
html(结果);
countries.append(allcountries);///首先是all选项
var w=$('#country_id:selected')。val();///w是其他组合的所选选项的值
countries.find('option[value='+w+']')).attr('selected','selected');///这将查找一个值为w的选项,如果存在,则标记为selected
}

为什么要使用
attr('selected',true)
for?我想既然我使用了.get函数,很明显我说的是一个url参数(用户上次搜索某物时执行的查询)。无论如何,我发现了一个传统的javascript函数,它可以获取url参数并解决了这个问题。谢谢你花时间回答我。通过你的回答,我丰富了我的jquery知识!
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
}