简体   繁体   English

jQuery:如何根据数值对列表文本进行排序

[英]jQuery: how to sort list text taking into account numerical values

I am using the following script (jQuery 2.1.1) to sort a list with text and numerical values.我正在使用以下脚本 (jQuery 2.1.1) 对包含文本和数值的列表进行排序。 In theory, sorting works because between "iPhone 11" and "iPhone 6", "iPhone 1" comes before "iPhone 6" but in the real world that does not make sense because 6<11 and "iPhone 6"<"iPhone 11".理论上,排序有效是因为在“iPhone 11”和“iPhone 6”之间,“iPhone 1”排在“iPhone 6”之前,但在现实世界中这没有意义,因为 6<11 和“iPhone 6”<“iPhone 11” ”。

$('ul').children("li").sort(function(a, b) {
var A = $(a).text().toUpperCase();
var B = $(b).text().toUpperCase();
return (A < B) ? -1 : (A > B) ? 1 : 0;
}).appendTo('ul');

How sorting should be:应该如何排序:

iPhone 6
iPhone 8
iPhone 11
iPhone 12
samsung galaxy s8
samsung galaxy s10
samsung galaxy s20

what sorting returns:什么排序返回:

iPhone 11
iPhone 12
iPhone 6
iPhone 8
samsung galaxy s10
samsung galaxy s20
samsung galaxy s8

What would the best approach be?最好的方法是什么? I am thinking of stripping all text and sort based on the integers left but if I did that, in the current list that would make the "galaxy" models appear between "iphone" models (which also makes no sense) like so:我正在考虑剥离所有文本并根据剩下的整数进行排序,但如果我这样做,在当前列表中将使“银河”模型出现在“iphone”模型之间(这也没有意义),如下所示:

iPhone 6
iPhone 8
samsung galaxy s8
samsung galaxy s10
iPhone 11
iPhone 12
samsung galaxy s20

Since you have to sort the text where it includes numbers, then do:由于您必须对包含数字的文本进行排序,因此请执行以下操作:

return A.localeCompare(B, false, {
  numeric: true
})

You can find more information on localCompare and the options here您可以在此处找到有关 localCompare 和选项的更多信息

So you code will look like:所以你的代码看起来像:

$('ul').children("li").sort(function(a, b) {
  var A = $(a).text().toUpperCase();
  var B = $(b).text().toUpperCase();
  return A.localeCompare(B, false, {
    numeric: true
  })
}).appendTo('ul');

Demo演示

 $('ul').children("li").sort(function(a, b) { var A = $(a).text().toUpperCase(); var B = $(b).text().toUpperCase(); return A.localeCompare(B, false, { numeric: true }) }).appendTo('ul');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>iPhone 6</li> <li>iPhone 8</li> <li>samsung galaxy s8</li> <li>samsung galaxy s10</li> <li>iPhone 11</li> <li>iPhone 12</li> <li>samsung galaxy s20</li> </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM