重新订购表格列?
有没有人知道使用jQuery重新排序表列的方法?
我不是指排序 – 我的意思是在表格中左右移动整个列。
我知道优秀的可拖动插件 ,但我不需要允许用户移动列的东西,我需要一些可以以可配置的方式进行重新排序的东西。
想法是遍历表的所有行(tr)并交换所需的td。 让我们交换第2列和第4列:
$('table tr').each(function() { var tr = $(this); var td1 = tr.find('td:eq(1)'); // indices are zero-based here var td2 = tr.find('td:eq(3)'); td1.detach().insertAfter(td2); });
我希望这有帮助。
此代码应该适合您。
$("table tr").each(function () { $(this).find("td").eq(1).after($(this).find("td").eq(0)); });
编辑:如果您将$(this).find(“td”)分配给变量,这将提供更好的性能。 但背景下降到一个单一的tr。 所以我认为仅仅提出这个想法就足够了。
$("table tr").each(function () { var rows = $(this).find("td"); rows.eq(1).after(rows.eq(0)); });
通过阅读可拖动插件的源代码,作者提到实际移动表列的算法诞生于对comp.lang.javascript新闻组的讨论。 那里的讨论在这里: 交换表列 。
在该线程中,OP不会询问重新排序的UI方面,而是帮助调试他已经编写的交换两列的函数。 在讨论的后面,它开发成代码,使您能够传递特定的列排序,并让代码计算从当前排序到指定排序的所有必要的交换/移动。
这不是jQuery(大多数关于cljs的海报都不喜欢它和大多数其他JS框架),因此它的代码可以满足您的需求,然后包含在任何地方。
我将它与jQueryUI结合起来,以获得一些很棒的拖放操作:
(function() { var local = {}; local.containment = 'parent'; local.revert = true; $('body thead th').draggable(local); $('body thead th').droppable({ drop: dropZone }); function dropZone(myEvent, myUI ) { var head = {}; head.dragIndex = myUI.draggable.index(); head.dropIndex = $(this).index(); head.rows = $(this).closest('thead').find('tr'); head.cellIndex = head.rows.find('th').length-1; head.rows.each(processTableHeaderRows); function processTableHeaderRows(index, element) { var row = {} row.tr = $(element); row.drag = row.tr.find('th:eq(' + head.dragIndex + ')'); row.drop = row.tr.find('th:eq(' + head.dropIndex + ')'); if (head.dropIndex === head.cellIndex) { row.drag.detach().insertAfter(row.drop); } else { row.drag.detach().insertBefore(row.drop); } } // Same thing here for td instead of th $(this).closest('table').find('tbody > tr').each(processRows); function processRows(index, element) { var row = {}; row.tr = $(element); row.drag = row.tr.find('td:eq(' + head.dragIndex + ')'); row.drop = row.tr.find('td:eq(' + head.dropIndex + ')'); if (head.dropIndex === head.cellIndex) { row.drag.detach().insertAfter(row.drop); } else { row.drag.detach().insertBefore(row.drop); } } } })();
试图让它在jsFiddle中工作,但我不能。 虽然在我的网站上工作 !