繁体   English   中英

使用jQuery构建选择/下拉optgroup问题

[英]issue building select/drop-down optgroup with jquery

我想将<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

    }
});

我的console.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM