使用jquery发布构建选择/下拉optgroup



我想将<optgroup>添加到JQuery的下拉列表中。选项工作正常,但我无法让选项组工作。

HTML:

<select name="DropDownID" id="DropDownID">
<optgroup label="Foo">
<option style="alignment: center" value="<%= alertGroup.colorValue %>" id="red7" selected disabled hidden><%= alertGroup.colorName %></option>
</optgroup>
</select>

JQuery:

$("#DropDownID")
colorBuild(function (result) {
var Color = result;
for (var i = 0; i < Color.Data.length; i++) {
$("#DropDownID").append($("<optgroup></optgroup>").attr('label', Color.Data[i].ColorText)); //<-- This is my issue
$("#DropDownID").append($("<option></option>").val(Color.Data[i].RgbValue).text(Color.Data[i].ColorText).html(Color.Data[i].ColorName)); //<-- This is working fine
}
});

我的控制台.log

{element: n.fn.init(1), index: 0, value: "df514f", label: "Red", optgroup: "Foo", …} //<-- this is coming from static HTML
56d6736dfe2cf81830b7ec0f:124 {element: n.fn.init(1), index: 1, value: "df514f", label: "Red", optgroup: "", …} //<-- I want to be able to add a value here with JQuery code above
56d6736dfe2cf81830b7ec0f:124 {element: n.fn.init(1), index: 2, value: "CD69C9", label: "Orchild", optgroup: "", …}

这就是我获取值的方式:

function GetSelectedItem(el)
{
var e = document.getElementById(el);
color = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
colorName = e.options[e.selectedIndex].text;
colorValue = e.options[e.selectedIndex].value;
optgroupValue = e.options[e.selectedIndex].optgroup; //<-- this is resolving as undefined
}

创建组,使用标签命名,然后将每个选项添加到组中?

$("#DropDownID")
colorBuild(function (result) {
var Color = result;
//create a constant for element
const $sel = $('#DropDownID');
//create a variable to hold our optgroup
var group = $('<optgroup/>');
//assign label to optgroup and append to select element
group.attr('label', 'Foo2').appendTo($sel);

for (var i = 0; i < Color.Data.length; i++) {
//probably only need .html here, anyway, append to group
$('<option />').val(Color.Data[i].RgbValue).text(Color.Data[i].ColorText).html(Color.Data[i].ColorName).appendTo(group);
}
}

并获取选定的optgroup。。。

optGroup = e.options[this.selectedIndex].parentNode.label

最新更新