在某个单元格上按字母顺序将行插入表格

我使用jQuery在数据库插入后将行插入表中。 当页面加载时,表格按特定单元格的字母顺序排序(见下文)。 当我使用jQuery插入一个新行时,我希望能够按字母顺序插入它。

所以例如我有一个表格,其中

元素类似于:

   Edit  Document A Description of Document A    No classes are currently associated with this document.      Edit  Document B Description of Document B     CLASS111 Description of CLASS101     CLASS333 Description of CLASS333     Edit  Document D Description of Document D    No classes are currently associated with this document.    

目前,当将新类行插入给定文档的

我使用.append()函数,当插入新文档时,我使用.after()

使用jQuery我希望能够按字母顺序在类号或文档名称上插入类或文档(适用于插入的内容)。

因此,例如,我希望能够为文档C插入新的

,或者将新类添加到文档B,其类号为CLASS222。

我怎样才能做到这一点?


更新:这是我目前用于为其中一个文档插入新类的代码:

  newClassesRows += $('#docsTable a[name="' + docID + '"]').closest('tr').after('' + '' + '' + '' + classNumber + '' + '' + className + '' + ''); 

正如您所看到的,找到了正确的文档$('#docsTable a[name="' + docID + '"]').closest('tr') ,所以我需要查看所选行的第三个td元素,检查文本并以某种方式确定变量classNumber与其他classNumbers按字母顺序排列的位置。

这是一种可能对您有用的方法(未经测试且不在我的脑海中)。 这仅适用于主标题“文档”行,但如果它适用于您,我相信您也可以将该想法调整到内部行。

首先,一个便利function,以构建适合您的模式的“文档”行。 大概你已经有了生成这些行的东西:

 var makeDocRow = function(name, description) { return $('\ Edit\ \ ' + name + '\ ' + description + '\ '); }; 

接下来,添加新文档行的函数:

 var addDocRow = function(name, description) { var counter = 0; // so we know when we've reached the end // assumes it's already sorted $('#main').find('tr.docRow').each(function() { counter++; if ($(this).find('td:eq(2)').html() >= name) { /* Have we found the right slot for the new document by name? td:eq(2) refers to the table cell containing the name for comparison Assumes the table is always sorted to start */ $(this).parent().before(makeDocRow(name, description)); // build/add row return false; // break out of each() since we're done } // Handle case where we've reached the end, but we're still in the loop. // This means the new row is alphabetically last, so insert after if ($(this).closest('table').find('tr.docRow').length === counter ) { $(this).parent().after(makeDocRow(name, description)); } }); }; 

在您的代码中,当您要插入新行时:

 addDocRow('Document C','Document C Description'); addDocRow('Document Z','Document Z Description'); 

这肯定会变得更好,未经测试,并且不在我的头顶,但也许它会有所帮助。


编辑:扔进一个小提琴。 似乎工作。 http://jsfiddle.net/redler/fhkWT/

这是我在之前的一个项目中完成的一种方法。

只需将行附加到tbody即可。 将每行的索引作为数据属性。 如下所示,以任何对象数组的forms获取要对其进行排序的列的数据值。

 var trs = [['data', 0], ['data', 1]];//0, 1 are the row indexes before sort. 

通过提供自定义排序方法对此数组进行排序。 排序后,您可以遍历此数组并将行追加到同一个表中。

 var tbody = $('tbody', fromYourTable); $.each(trs, function(index, tr){ //find the row by using tr[1] which contains the index in the unsorted table tbody.append(tbody.find('tr[index="'+tr[1]+'"]')); });