我有一个关于 select2 下拉加载微调器的解决方案,用于 Ajax 调用。
通过 2 个简单的功能,我们将加载图标放在下拉菜单中
添加引用(select2下拉cdn)
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
HTML
div class="row">
<div class="col-md-4">
<select class="js-example-basic-single" name="state" id="country">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
<option value="ZB">Zimbamwe</option>
<option value="TR">Türkiye</option>
</select>
</div>
<div class="col-md-4">
<select class="js-example-basic-single" name="state" id="city"></select>
</div>
<div class="col-md-4">
<select class="js-example-basic-single" name="state" id="district"></select>
</div>
addLoadSpiner
此函数用于在下拉列表中添加或显示微调器 gif。加载微调器作为 html 元素动态创建并添加到下拉列表中。如果之前已添加,则仅显示在屏幕上。
function addLoadSpiner(el) {
debugger;
if (el.length > 0) {
if ($("#img_" + el[0].id).length > 0) {
$("#img_" + el[0].id).css('display', 'block');
}
else {
var img = $('<img class="ddloading">');
img.attr('id', "img_" + el[0].id);
img.attr('src', 'http://www.lettersmarket.com/uploads/lettersmarket/blog/loaders/common_gray/ajax_loader_gray_512.gif');
img.css({ 'display': 'block', 'width': '25px', 'height': '25px', 'z-index': '100', 'float': 'right' });
img.prependTo(el[0].nextElementSibling);
}
el.prop("disabled", true);
}
}
hideLoadSpinner
添加 css css('display', 'none') 从屏幕中删除
function hideLoadSpinner(el) {
if (el.length > 0) {
if ($("#img_" + el[0].id).length > 0) {
setTimeout(function () {
$("#img_" + el[0].id).css('display', 'none');
el.prop("disabled", false);
}, 500);
}
}
}
使用 Ajax 加载数据
最后,Loading spinner 出现在显示屏上,直到 Ajax 完成
$.ajax({
url: "/Home/GetCities",
data: JSON.stringify({
'countryId': $("#country option:selected").val()
}),
type: 'POST',
cache: false,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result) {
var dbSelect = $('#city');
addLoadSpiner(dbSelect);
dbSelect.empty();
$.each(result, function (index, item) {
dbSelect.append("<option value='" + item.id + "'>" + item.text + "</option>")
});
hideLoadSpinner(dbSelect);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});