如何在JavaScript中对NodeList进行重新排序/排序? [英] How can I reorder/sort a NodeList in JavaScript?
问题描述
我有一个我认为应该是一个简单的问题;让我快速解释一下:
I have what I think should be a straightforward question; let me quickly explain:
在我的JavaScript中,food.xml
的读取方式为:
In my JavaScript, food.xml
is read in with:
getMenuXml.open("GET","food.xml",false);
getMenuXml.send();
xmlDoc=getMenuXml.responseXML;
xmlFoodList = xmlDoc.getElementsByTagName("food");
所以现在我有了一个包含所有食物元素的NodeList xmlFoodList
.到目前为止很好.问题是我想根据内部的元素<category>
对节点进行排序.我可以这样阅读:
so that now I have a NodeList xmlFoodList
with all the food elements. Great so far. The problem is I want to sort the nodes based on an element <category>
inside. I can read that with:
xmlFoodList[i].getElementsByTagName("category")[0].childNodes[0].nodeValue
稍后在我的代码中,食物项将显示在列表中,并且正如您期望的那样,我希望将同一类别的食物一起列出.因此,我的问题是:如何根据类别对xmlFoodList
中的节点重新排序?
Later in my code, the food items are displayed in a list, and as you'd expect, I want food of the same category to be listed together. So, my question is: How can I reorder the nodes in xmlFoodList
based on their category?
注意:我无法更改传入的food.xml
,并且由于列表已填充,我不想编辑以后的代码来进行排序.我不想将NodeList转换为数组,因为我不得不重写很多以后的代码.性能实际上并没有太大的关系,因此可以随意克隆/嵌套所有所需的循环.谢谢您的宝贵时间.
Notes: I can't change food.xml
coming in, and I don't want to edit my later code to do the sorting as the list is populated. I don't want to convert the NodeList to an array, since I'd have to rewrite a lot of later code. Performance isn't actually much of a concern, so feel free to clone/nested loop all you want. Thanks for your time.
推荐答案
如果首先将它们转换为数组,则可以对NodeList的元素进行排序:
You can order the elements of the NodeList, if you convert them to an array first:
var foods = xmlDoc.getElementsByTagName("food");
var foodsArray = Array.prototype.slice.call(foods, 0);
然后您可以使用sort
方法:
foodsArray.sort(function(a,b) {
var aCat = a.getElementsByTagName("category")[0].childNodes[0].nodeValue;
var bCat = b.getElementsByTagName("category")[0].childNodes[0].nodeValue;
if (aCat > bCat) return 1;
if (aCat < bCat) return -1;
return 0;
});
但是,这在很大程度上取决于您的XML模式-例如,如果您的食物属于多个类别,那么它们只能按上述代码中的第一个类别进行排序.
This is highly dependent on your XML schema though - if, for example, you had foods which were in more than one category they would only be sorted by the first category in the code above.
这篇关于如何在JavaScript中对NodeList进行重新排序/排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!