Move tr by index to a new position

2020-06-28 01:18发布

问题:

I have a table that has a fixed layout of rows. Each row has unique identifier. When the data is returned from the database it has a different order for the rows in that table. The returned data has the same index that exists in the fixed layout so I can find the matching row in the fixed table. I need to move the rows in the fixed table layout to match the order of rows in the data.

Table Layout:

<table>
    <tr id="a1"><td>Some Value1</td></tr>
    <tr id="a2"><td>Some Value2</td></tr>
    <tr id="a3"><td>Some Value3</td></tr>
    <tr id="a4"><td>Some Value4</td></tr>
    <tr id="a5"><td>Some Value5</td></tr>
</table>

So if the order from the database is a3,a4,a5 I need the table to look like this.

<table>
    <tr id="a3"><td>Some Value1</td></tr>
    <tr id="a4"><td>Some Value2</td></tr>
    <tr id="a5"><td>Some Value3</td></tr>
    <tr id="a1"><td>Some Value4</td></tr>
    <tr id="a2"><td>Some Value5</td></tr>
</table>

Is it possible to move the rows by row index or perhaps if I clone the row, move it to a specific row index and then remove the old row/position with something like this.

var clonedRow = $("#tbl_lp_Forms > tbody > tr[class=" + myformurl + "] ").clone(true);
$('#tbl_lp_Forms tr:first').before(clonedRow);

Hope you can help!

回答1:

First of all - if you want move row you don't need to clone it. When you select some html element and append/prepend it other place then it will be removed from old position - this is how DOM works. So according to html you wrote, when you do this:

var $table = $('table');
$table.prepend($('#a3'));

then row with id 'a3' will be removed from its old position and placed on the beginning of table.

If we assume that you have array with order you want to achive:

var order = ['a3', 'a4', 'a5', 'a1', 'a2']; 

then to sort rows according to this table you have to simply iterate from the last element in this array, get row with current id from table, and place it on the beginning like this:

var order = ['a3', 'a4', 'a5', 'a1', 'a2']; 
var $table = $('table');        

for (var i = order.length; --i >= 0; ) {
    $table.prepend($table.find('#' + order[i]));
}

And when you want to move one row and place in before other:

var $rowa = $('#a1');
var $rowb = $('#a5');
$rowb.insertBefore($rowa);

// or even like this
$('#a5').insertBefore('#a1');


回答2:

Why are you trying to do the sorting in JS? Just save the sort order in the database when they save, and then ORDER BY that column when you select the data for display when they come back. You can normalize this by putting the indexes in a 1:M table and joining it to your main data table, or you can store it as a denormalized string with a delimiter in the main data table itself (not recommended).