首页 > 解决方案 > 如何根据值将 css 类添加到选择列表的选项中 - 使用 jQuery

问题描述

技术:

asp.net MVC 5 .net 框架 + jQuery

案子:

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

问题:

将所有选项附加到选择列表后,我试图根据它们的值将 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>

jQuery ajax 调用:

$.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.Valuethis.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');
                }
            });

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

标签: jquerycssasp.net-mvc-5

解决方案


谷歌搜索异常导致我得到另一个 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');
                }

推荐阅读