Rumah > Soal Jawab > teks badan
贴出我的代码,但是感觉这个方法太low,求教更好的方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>test5</title>
</head>
<body>
<select id="myselect" size="5">
<option val="c">选项C</option>
<option val="d">选项D</option>
<option val="b">选项B</option>
<option val="e">选项E</option>
<option val="a">选项A</option>
</select>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var arr = [];
var html = '';
$("#myselect option").each(function() {
arr.push($(this).attr("val"));
});
for(var i=0; i<arr.sort().length; i++) {
html += '<option val='+arr[i]+'>选项'+arr[i].toUpperCase()+'</option>';
}
$("#myselect").empty().append(html);
</script>
</body>
</html>
PHPz2017-04-10 17:40:37
这个题目是为了考察arr.sort([compareFunction])
吧。
compareFunction
Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
$('#myselect').html($('#myselect > option').sort(function(a,b){return $(a).attr('val') > $(b).attr('val')}));