javascript - 请教jq排序问题
本文介绍了javascript - 请教jq排序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
贴出我的代码,但是感觉这个方法太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>
解决方案
这个题目是为了考察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')}));
这篇关于javascript - 请教jq排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文