当我从多个选择框中选择时,我需要选择项目的顺序应该与我选择选项的方式保持一致。
这意味着,现在,当我选择February, March, January
时,我框中所选项目的顺序为January, February, March
。但我需要保留我选择的顺序。在这种情况下February, March, January
。
$('select').select2({
placeholder: 'Select a month'
});

<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.full.js"></script>
<select multiple="multiple" style="width: 300px">
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
&#13;
答案 0 :(得分:1)
Select2不直接支持。但你仍然可以解决这个问题。您需要重新排序<option>
,以便在选择时按顺序获取所选选项。并且,当他们从选择中删除时,再次重新排序。
$('select').select2({
placeholder: 'Select a month'
});
$("select").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
window.setTimeout(function () {
if ($("select").find(":selected").length > 1) {
var $second = $("select").find(":selected").eq(-2);
$element.detach();
$second.after($element);
} else {
$element.detach();
$("select").prepend($element);
}
$("select").trigger("change");
}, 1);
});
$("select").on("select2:unselect", function (evt) {
if ($("select").find(":selected").length) {
var element = evt.params.data.element;
var $element = $(element);
$
("select").find(":selected").after($element);
}
});
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.full.js"></script>
<select multiple="multiple" style="width: 300px">
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>