Re-order table columns?

后端 未结 4 862
北荒
北荒 2021-02-03 10:55

Does anyone know a way to re-order table columns, using jQuery?

I don\'t mean sort - I mean dynamically move entire columns left or right in a table.

I\'m aware

4条回答
  •  隐瞒了意图╮
    2021-02-03 11:33

    I combined it with jQueryUI to get some great drag and drop action:

    (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);
                }
            }
        }
    })();
    

    Tried to get it to work in jsFiddle, but I couldn't. Works on my website though!

提交回复
热议问题