您好我需要对国家/地区列表进行排序,以便法国始终位于列表的首位。
以下是列表的输入顺序。
<select id="countriesList" name="countriesListName">
<option value="US">USA</option>
<option value="DE">Germany</option>
<option value="FR">France</option>
<option value="DM">Denmark</option>
<option value="">Choose Countries</option>
</select>
答案 0 :(得分:4)
$(function() {
var $list = $("#countriesList"), $opts = $("option",$list);
$opts.sort(function(a, b) {
a = $(a).val();
b = $(b).val();
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
$list.html($opts);
// insertBefore or prepend
$('option[value = "FR"]', $list).insertBefore($("option", $list).first());
$('option[value = ""]', $list).insertBefore($("option", $list).first());
$list.get(0).selectedIndex=0; // or 1 to select France
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="countriesList" name="countriesListName">
<option value="US">USA</option>
<option value="DE">Germany</option>
<option value="FR">France</option>
<option value="DM">Denmark</option>
<option value="">Choose Countries</option>
</select>
&#13;
答案 1 :(得分:0)
完整的解决方案:
$(function() {
var options = $('#countriesList option');
options.sort(function(a, b) {
if (a.value > b.value) {
return 1;
}
else if (a.value < b.value) {
return -1;
}
else {
return 0;
}
})
$("#countriesList").empty().append(options);
// Vive la France!
$('#countriesList option[value="FR"]').insertAfter($('#countriesList option:first'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="countriesList" name="countriesListName">
<option value="US">USA</option>
<option value="DE">Germany</option>
<option value="AZ">Azerbaijan</option>
<option value="FR">France</option>
<option value="DM">Denmark</option>
<option value="">Choose Countries</option>
</select>
&#13;
在:
后:
答案 2 :(得分:0)
function myFunction(country) {
var select = document.getElementById("selectFrance");
var opts = select.options.length;
if ((select.options[1].value !== "FR")){
for (var i=0; i<opts; i++){
if (select.options[i].value == "FR"){
select.insertBefore(select[i],select[1]);
break;
}
}
}
}