我将select2与Ajax一起使用,并且效果很好。但是我不能做以下事情:
我有一个php服务器,当我用Select2(由Ajax)搜索时,它将返回值。在正常情况下,Select2将所有搜索结果都用黑色打印,但是我希望将结果与其他局部变量进行比较,然后将它们中的一些局部变量打印为蓝色(如果该值是新的,则可以在蓝色上打印)。
In normal condition它以黑色打印,但我希望以蓝色打印一些单词。
我的Select2 Ajax代码是:
$("#idSelectorTypology").select2({
cache: true,
tags: true,
tokenSeparators: [','],
ajax: {
url: './../../back-end/switch-ajax-listening/switch-ajax-listening.php',
type: "post",
dataType: 'json',
delay: 250,
data: function (params)
{
return {
searchTerm: params.term, // search term
actionId: "getSelector",
jsonField: "idSelectorTypology"
};
},
processResults: function (response)
{
return {
results: response,
id: response.term,
text: response.term + " (new)",
newOption: true
};
},
},
createTag: function (params)
{
var term = $.trim(params.term);
if(term==="-")
{
return {
id: term,
text:term,
};
}
if (term === '')
{
return null;
}
//console.log(term.length);
if(term.length>50)
{
alertError("The typology must be less than 50 char");
return null;
}
return {
id: term,
text: term + ' (new)'
};
},
});
您有一些想法可以做到这一点吗?
例如,当值为新值时,以蓝色打印。
答案 0 :(得分:0)
您可以将输入事件委托给输入 select2-search__field :
$(document).on('input', '.select2-search__field', function(e) {
if ($(this).closest('.select2-container').find('li:contains("'+ this.value + ' (new tag)")').length > 0) {
$(this).addClass('blueColor');
} else {
$(this).removeClass('blueColor');
}
})
$(".js-example-tags").select2({
tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term + ' (new tag)', // add text....
newTag: true // add additional parameters
}
}
}).on('change select2:close', function(e) {
$(this).next('.select2-container').find('.select2-selection__rendered').text(function(idx, txt) {
if (txt.indexOf(' (new tag)') != -1) {
$(this).addClass('blueColor');
}
return txt.replace(' (new tag)', '');
})
});
$(document).on('input', '.select2-search__field', function(e) {
if ($(this).closest('.select2-container').find('li:contains("'+ this.value + ' (new tag)")').length > 0) {
$(this).addClass('blueColor');
} else {
$(this).removeClass('blueColor');
}
})
.js-example-tags {
width: 100%;
}
.blueColor {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
<select class="form-control js-example-tags">
<option selected="selected">black 1</option>
<option>white 2</option>
<option>white 3</option>
<option>black 4</option>
</select>