javascript - 请教jq排序问题
PHP中文网
PHP中文网 2017-04-10 17:38:37
0
1
245


贴出我的代码,但是感觉这个方法太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>
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
PHPzhong

这个题目是为了考察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')}));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template