我想按First Character排序选项。 例如如果我搜索'banana',那么所有4个选项都将使用select2搜索,但我首先想要'Sbanana1'。
那么有没有我用“S”(特定)字符对select2结果进行排序的选项, 所以从's'选项开始将首先显示。
<button type=button>Sort Options</button>
<select class='whatever'>
<option value='Banana'>Banana1</option>
<option value='Hello'>Banana2</option>
<option value='Sugar Cane'>SBanana1</option>
<option value='Palm Oil'>SBanana2</option>
</select>
答案 0 :(得分:4)
使用Select2选项API v4.0 - 排序
$('.whatever').select2({
sorter: function(data) {
/* Sort data using lowercase comparison */
return data.sort(function(a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a[0] == 's' && b[0] == 's') {
return compare(a, b)
} else if (a[0] == 's') {
return -1;
} else if (b[0] == 's') {
return 1;
} else {
return compare(a, b)
}
});
}
});
function compare(a, b) {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
}
&#13;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" integrity="sha256-xqxV4FDj5tslOz6MV13pdnXgf63lJwViadn//ciKmIs=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js" integrity="sha256-FA14tBI8v+/1BtcH9XtJpcNbComBEpdawUZA6BPXRVw=" crossorigin="anonymous"></script>
<select class="whatever">
<option value="Banana">Banana1</option>
<option value="Hello">Banana2</option>
<option value="Sugar Cane">SBanana1</option>
<option value="Palm Oil">SBanana2</option>
</select>
&#13;
使用Select2选项API v3.x - sortResults
$('.whatever').select2({
sortResults: function(data) {
/* Sort data using lowercase comparison */
return data.sort(function(a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a[0] == 's' && b[0] == 's') {
return compare(a, b)
} else if (a[0] == 's') {
return -1;
} else if (b[0] == 's') {
return 1;
} else {
return compare(a, b)
}
});
}
});
function compare(a, b) {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
}
&#13;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.css" integrity="sha256-ijlUKKj3hJCiiT2HWo1kqkI79NTEYpzOsw5Rs3k42dI=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.js" integrity="sha256-7A2MDY2eGSSUvgfbuH1IdzYk8qkEd3uzwiXADqPDdtY=" crossorigin="anonymous"></script>
<select class="whatever">
<option value="Banana">Banana1</option>
<option value="Hello">Banana2</option>
<option value="Sugar Cane">SBanana1</option>
<option value="Palm Oil">SBanana2</option>
</select>
&#13;