使用 URL 参数填充下拉列表的第一个选项

populate first option of dropdown with URL parameter

我正在尝试根据提供的 URL 参数设置下拉菜单的第一个选项 select。

我正在使用以下代码获取 URL 参数:

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = window.location.search.substring(1),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;

  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');

    if (sParameterName[0] === sParam) {
      return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
    }
  }
  return false;
};

URL可以这样读:

https://development.mycompany.com/project/home.php?profile=profile1,profle2&region=&rep=JOHN%20BEASLEY

然后我可以调用 getUrlParameter() 函数来获取 rep 参数:

var rep = getUrlParameter('rep');

console.log(rep);

$('#rep').val(rep); // <-- my attempt to set the first option of the dropdown

我可以在控制台中看到 rep 变量。但是,当尝试设置下拉列表的第一个选项时 select,它仍然是空白。

这是下拉菜单:

<select class="form-control rep" id="rep"></select>    

我应该能够看到 'JOHN BEASLEY' 作为下拉列表中的 selected 选项。

下拉列表包含 'JOHN BEASLEY' 以及其他代表,但它应该显示为最初 selected。我很困惑为什么这不起作用。

我做错了什么,我该如何解决?

*** 编辑 ***

我最初使用以下函数填充下拉列表:

function initializeSelect($select, uri, adapt){     
$.getJSON( uri, function( data ) {
    $select.empty().append($('<option>'));      
    $.each(data, function(index, item) {
        var model = adapt(item);
        var $option = $('<option>');
        $option.get(0).selected = model.selected;
        $option.attr('value', model.value)
            .text(model.text)
            .appendTo($select);                     
    });
});
};

然后我像这样填充下拉列表:

initializeSelect($('#rep'), 'api/getReps.php', function (item){ 
return {
    value: item.fullname,
    text: item.fullname,
    style: 'color:black'
}
}); 

使用上面的方法,下拉列表成功填充了我的 dB table 中的所有选项。

选项 JOHN BEASLEY 在下拉列表中可用。

也许你可以只在 select 初始化后设置 select.value,像这样:

function initializeSelect($select, uri, adapt){     
    $.getJSON( uri, function( data ) {
        $select.empty().append($('<option>'));      
        $.each(data, function(index, item) {
            var model = adapt(item);
            var $option = $('<option>');
            $option.get(0).selected = model.selected;
            $option.attr('value', model.value)
                .text(model.text)
                .appendTo($select);                     
        });
        $select.val(getUrlParameter('rep'));
    });
};