如何根据内容对嵌套的div进行排序 [英] How to sort nested divs depending upon content
问题描述
我有以下HTML架构
<div id="txm_left_column">
<div class="id">
<h2>Some Name1</h2>
<div>// another list</div>
</div>
<div class="id">
<h2>Some Name2</h2>
<div>// another list</div>
</div>
</div>
用户可以在该列表中添加项目,并且所有 Divs
应按 h2
中的名称按字母顺序排列。
我有两个选项
The user is able to add items to that list and all Divs
should be in alphabetical order by the name in the h2
.
I've two options
1)我需要能够在字母顺序正确的2个div之间插入一个新项目
1) i need to be able to insert a new item in between the 2 divs where the alphabetical order is correct
2)完全整理清单。
2) re organise the list entirely.
我的方法是选项2,按字母顺序按<$ c $中的名称对 Divs
进行排序c> h2
My approach was option 2, to sort the Divs
in alphabetical order by the name in the h2
我想出了以下代码来尝试订购它但是这段代码创建了一个新的有序列表 H2
s没有 div
s。然后我试着通过使用相同的函数来做选项1)但是试图插入像这样的(upA< upB)? -1:(NEW_ITEM_NAME> upB)? 1:0
但这会导致问题,因为这不会破坏排序。
I came up with the following code to try to order it but this code creates a new List of ordered H2
s without the div
s. then I tried to do option 1) by using the same function but trying to insert into something like this (upA < upB) ? -1 : (NEW_ITEM_NAME> upB) ? 1 : 0
but that will cause a problem as that doesn't break the sort.
我想知道两件事,一件是我怎么能打破排序,因为0不会破坏它。或者我如何组织我的清单的任何帮助。
I was wondering 2 things, one is how could i break the sort as return 0 would not break it. or any help on how could i organise my list.
谢谢
jQuery("#txm_left_column > div").children("h2").sort(function(a, b) {
var upA = jQuery(a).text().toUpperCase();
var upB = jQuery(b).text().toUpperCase();
return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
}).appendTo(selector);
推荐答案
但此代码创建没有div的新订单H2列表。
but this code creates a new List of ordered H2s without the divs.
那是因为你正在排序 h2
元素而不是 div
元素:
That's because you are sorting h2
elements and not the div
elements:
jQuery("#txm_left_column > div").sort(function(a, b) {
var upA = jQuery('> h2', a).text().toUpperCase();
var upB = jQuery('> h2', b).text().toUpperCase();
// ...
}).appendTo(selector);
这篇关于如何根据内容对嵌套的div进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!