【发布时间】:2021-03-10 15:03:59
【问题描述】:
我正在尝试根据提供的 URL 参数设置下拉选择的第一个选项。
我正在使用以下代码获取 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;
};
网址可能如下所示:
https://development.mycompany.com/project/home.php?profile=profile1,profle2®ion=&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 class="form-control rep" id="rep"></select>
我应该能够在下拉菜单中看到“JOHN BEASLEY”作为选定选项。
下拉列表包含“JOHN BEASLEY”以及其他代表,但它应该显示为最初选择的样子。我很困惑为什么这不起作用。
我做错了什么,我该如何解决?
*** 编辑 ***
我最初使用以下函数填充下拉列表:
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 表中的所有选项。
JOHN BEASLEY 选项在下拉列表中可用。
【问题讨论】:
-
<select>显示为空?您是在尝试创建这样的<option>,还是已经存在具有该值的<option>? -
该选项已存在于下拉菜单中。我正在尝试获取下拉菜单以将所选选项显示为 URL 中的参数。
-
那么请按照minimal reproducible example 提供
<option>html。另一种可能性是您正在运行<select>存在之前显示的代码 -
@charlietfl - 我更新了我的问题以包含最初填充下拉列表的函数。
标签: javascript jquery url parameters dropdown