Move tr by index to a new position

淺唱寂寞╮ 提交于 2019-12-04 16:34:47

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');

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!