使用jQuery对存储在变量中的Div元素进行排序

我有一个存储在变量中的HTML dom元素。 HTML是使用jQuery从handlebar.js和JSON数据生成的。 我需要根据CSV中的值对其进行排序

var html = "
Qual
Exp
Edu
Int
Ref
Img
Obj
";

HTML通常很复杂,通常超过200行代码。 html将有很多div标签,有或没有id,嵌套div等。我在这里使用一个简单的表示法。

我在一个varibale中将sortorder作为csv

 var sortorder = "obj,exp,qual,edu,int,ref,img"; 

但是带有上述id的div标签将完全存在于生成的HTML中(var html肯定会有所有那些具有相应id的div。)为了保持简单,var html可能有超过100个div但是这7个div是

 
Qual
Exp
Edu
Int
Ref
Img
Obj/div>

根据var sortorder将defuffly存在于var html中的一些shuffled顺序。

我需要的是相同的var html,但那些div根据传递的值排序。 var html中的其他div不应该受到影响。

我想我已经足够简短地解释了我的要求,我已经发布了这个问题

如何使用jQuery从CSV列表中根据id对div元素进行排序?

但这种方法并不是一直都在运作。

这是一个使用Paolo Bergantino的swapWith函数的工作示例。

 // swapWith // from @Paolo Bergantino // https://stackoverflow.com/questions/698301/is-there-a-native-jquery-function-to-switch-elements/698386#698386 jQuery.fn.swapWith = function(to) { return this.each(function() { var copy_to = $(to).clone(true); var copy_from = $(this).clone(true); $(to).replaceWith(copy_from); $(this).replaceWith(copy_to); }); }; // return a jQuery object function sortDivsByIds($html, ids, current) { current = current || 0; // mark items that needs to be sorted if (current ==0) { $(ids).each(function(i,elem) {$("#" + elem, $html).addClass('sorter');}); } // reorder / iterates $('#' + ids[current], $html ).swapWith( $('.sorter', $html).eq(current) ); if (current+1 

用法

 var html = '
Qual
Exp
Edu
Int
dont sort me
Ref
dont sort me 2
Img
Obj
'; var sortorder = "obj,exp,qual,edu,int,ref,img"; var $htmlsorted = sortDivsByIds( $('
', {html:html}), sortorder.split(',')); alert($htmlsorted.html());

小提琴: http : //jsfiddle.net/yiernehr/GtEhj/1/