技术:
asp.net MVC 5 .net框架+ jQuery
案例:
我正在运行时构建选择列表,在该列表中,数据是通过ajax从控制器中获取的。数据以数据类型List<SelectListItem>
返回给ajax调用。然后使用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.');
}
});
UPDATE
通过将this.Value
更改为this.text
,现在可以获得所需的比较。调试器现在将引发异常:“ this.addClass不是函数”
所以现在我正在使用此代码:
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属性。
搜索异常导致我得到另一个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');
}