如何使用数字对列表中的元素进行排序?

时间:2014-03-10 04:53:07

标签: javascript jquery html

我正在尝试对此列表进行排序:

<div id="mainMenu">
    <span>Thing 5</span>
    <span>Thing 4</span>
    <span>Thing 7</span>
    <span>Thing 1</span>
    <span>Thing 5</span>
    <span>Thing 6</span>
    <span>Thing 3</span>
</div>

我试过了:

$('#mainMenu').sort(function(){
    $(this).children().sort();
});

我想按顺序排序:

<span>Thing 1</span>
<span>Thing 2</span>
<span>Thing 3</span>
<span>Thing 4</span>
<span>Thing 5</span>
<span>Thing 6</span>
<span>Thing 7</span>

2 个答案:

答案 0 :(得分:1)

试试这个,

$span = $('#mainMenu span').sort(function(a, b) {
    if ($(a).text() < $(b).text()) return -1;
    if ($(a).text() > $(b).text()) return 1;
    return 0;
});
$('#mainMenu').html($span);

Demo

答案 1 :(得分:1)

完美地试用此代码:

var mylist = $('#mainMenu');
var listitems = mylist.children('span').get();

listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
});
$.each(listitems, function(index, item) {
   mylist.append(item); 
});