2016-08-29 58 views
0

我卡住了这个问题一段时间。我有一个嵌套的列表,它的结构看起来像如何在Javascript中对复杂列表进行排序?

Volume1 
    Chapter4 
    Chapter3 
     Section3-6 
     Section3-1 
Volume2... 
... 

我要的是创造一个排序函数来排序的体积,章的一段。

那么,结果可能会像

Volume1 
    Chapter1 
     Section1-1 
.... 

所以我得到了一个复杂的HTML,这里是whole html。 我不知道如何交换这个复杂的div 我试图获取元素并将它们放入一个数组中。

var toSort = document.getElementById('volume5015').children; 
toSort = Array.prototype.slice.call(toSort, 0); 
+0

什么 '体积<(%)=体积[0]%>' 呢?不是这个jsp语法吗? – Manticore

+0

为什么不只是递归地进行排序并像通常那样对项目进行排序呢? – Michal

+0

您可能有更好的运气排序底层的数据结构,而不是HTML。 – georg

回答

0

我为你做了一个小提琴。

在我的代码中,我正在修整文本的空白区域,所以不会进行比较,但实际上如果您不需要,您并不需要。

var $items = $("#to-sort").children(); 
var $resultList = $("#list2"); 

sortMarkup($items, $resultList); 

function sortMarkup($elements, $output) { 
    $elements.sort(function(a, b) { 
    var contentA = getPureText(a).trim(); 
    var contentB = getPureText(b).trim(); 
    var okay = contentA.toUpperCase().localeCompare(contentB.toUpperCase()); 

    if($(a).children().length > 0) 
     sortMarkup($(a).children(), $(a)); 

    if($(b).children().length > 0) 
     sortMarkup($(b).children(), $(b)); 

    console.log("sorting ["+contentA+"] and ["+contentB+"] returned "+okay); 
    return okay; 
    }); 

    $output.append($elements); 
} 

function getPureText(elem) { 
    return $(elem).contents().filter(function() { 
    return this.nodeType == 3; 
    })[0].nodeValue; 
} 

此外,我正在使用输出列表,另一件不是必需的。随意修改您的需求!

拨弄https://jsfiddle.net/vincelord/sn42argq/

+0

感谢您给我一个方向,我认为每个标签都很难获得纯文本,我想我应该考虑对原始数据进行排序,然后将新数据添加到正确的位置。 –

相关问题