如何根据值将 css 类 添加到 select 列表的选项 - 使用 jQuery

How can I add css classes to a select list's options based on the value - using jQuery

技术:

asp.net MVC 5 .net 框架 + jQuery

案例:

我正在运行时构建一个 select 列表,其中数据是通过 ajax 从控制器获取的。 数据作为数据类型 List<SelectListItem> 返回到 ajax 调用。 然后使用 jQuery 动态构建 select 列表。这一切都很好并且有效。

问题:

将所有选项附加到 select 列表后,我尝试根据它们的值将 css 类 添加到选项。这就是我无法上班的原因。

我对在浏览器开发者工具中调试 js 仍然相当菜鸟,但在我看来,我所做的比较并不像我想象的那样。也许 if/else 比较是我弄错的地方!?

基础HTML:

<label for="EditBadge" class="form-label pt-00">Badge type</label>
<select class="form-control shadow mb-20" id="EditBadge" name="BadgeType">
</select>

jQueryajax调用:

$.ajax({
        url: '/OrderSetting/GetOrderTypeData/' + id,
        dataType: 'json',
        type: 'GET',
        async: true,
        cache: false,
        success: function (result) {
            $('#EditOrderType').val(result.OrderType);
            $('#EditLeadTime').val(result.DeliveryDays);
            $('#orderTypeId').val(result.OrderSettingId);


            let data = result.BadgeTypes; // The List<SelectListItem>
            let options = $("#EditBadge"); // The empty select list

            options.find('option').remove(); // Clear any options from a previous operation

            // Populate the select list
            options.append($("<option />").val('Default').text('Select badge type ...'));
            $.each(data, function () {
                if (this.Value !== 'Default') {
                    if (this.Selected === true) {
                        options.append($("<option />").val(this.Value).text(this.Text).attr('selected', 'selected'));
                    } else {
                        options.append($("<option />").val(this.Value).text(this.Text));
                    }
                }
            });

            // FROM HERE ON THIS IS WHERE IT ALL FAILS
            // Get all the added options
            let newOptions = $('#EditBadge > option');

            // Iterate the options, add css based on the value property of the options element
            newOptions.each(function () {
                if (this.Value === 'Success') {
                    this.addClass('badge badge-pill badge-success');
                }
                else if (this.Value === 'Warning') {
                    this.addClass('badge badge-pill badge-warning');
                }
                else if (this.Value === 'Danger') {
                    this.addClass('badge badge-pill badge-danger');
                }
            });


        },
        error: function (xhr) {
            alert('There was an error getting the entity data.');
        }
    });

更新

通过将 this.Value 更改为 this.text,我现在得到了所需的比较。调试器现在抛出异常:"this.addClass is not a function"

所以现在我正在使用这段代码:

let newOptions = $('#EditBadge > option');

            newOptions.each(function () {
                if (this.text === 'Success') {
                    this.addClass('badge badge-pill badge-success');
                }
                else if (this.text === 'Warning') {
                    this.addClass('badge badge-pill badge-warning');
                }
                else if (this.text === 'Danger') {
                    this.addClass('badge badge-pill badge-danger');
                }
            });

幸运的是,对于我的情况,文本和值 属性 是相同的。如果有人知道为什么 this.Value 不起作用,请在下面发表评论。我仍然想知道如何访问值 属性.

谷歌搜索异常让我找到了另一个 SO 答案,其中 this 关键字被包装在 jQuery $() 容器中。这样就可以了。 功能齐全的代码位现在显示为:

let newOptions = $('#EditBadge > option');

            newOptions.each(function () {
                if (this.text === 'Success') {
                    $(this).addClass('badge badge-pill badge-success');
                }
                else if (this.text === 'Warning') {
                    $(this).addClass('badge badge-pill badge-warning');
                }
                else if (this.text === 'Danger') {
                    $(this).addClass('badge badge-pill badge-danger');
                }