在Chrome中排序无序列表的列表项

时间:2012-04-03 15:43:41

标签: javascript jquery google-chrome sorting

我得到了这个代码,用于对有关其title属性的无序列表进行排序。

$('#list li').sort(function(a,b) {
    return $(a).attr('title') < $(b).attr('title');
}).appendTo('#list');

它在Firefox和IE上运行良好,但只要列表元素数超过10,就会在Chrome上失败(参见http://jsbin.com/atoput/4

是否有更好/更容易/更快速的方式对动态元素进行排序,你甚至可以解释一下Chrome在这里做了什么?

1 个答案:

答案 0 :(得分:4)

使用此:

$(document).ready(function() {
  var list  = $('#list');
  var items = list.children('li').get();
  items.sort(function(a, b) {
    var A = a.title;
    var B = b.title;
    return (A < B) ? -1 : (A > B) ? 1 : 0;
  });
  $.each(items, function(idx, itm) { list.append(itm); });
});

可以看到预览here

如果您希望列表按降序排序,请切换标志:

return (A > B) ? -1 : (A < B) ? 1 : 0;
相关问题