将索引移动到新位置 [英] Move tr by index to a new position

查看:131
本文介绍了将索引移动到新位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有固定行布局的表。每行都有唯一的标识符。从数据库返回数据时,它对该表中的行具有不同的顺序。返回的数据与固定布局中存在的索引相同,因此我可以在固定表中找到匹配的行。我需要移动固定表格布局中的行以匹配数据中的行顺序。

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

因此,如果数据库中的订单是a3,a4,a5我需要表格看起来像这样。

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

希望你能提供帮助!

推荐答案

首先 - 如果你想要移动行,你不需要克隆它。
当你选择一些html元素并在其他位置追加/前置它然后它将从旧位置移除 - 这就是DOM的工作方式。
所以根据你写的html,当你这样做时:

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

然后带有id'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']; 

然后根据此表对行进行排序,您只需从此数组中的最后一个元素进行迭代,从表中获取具有当前id的行,并将其放在开头,如下所示:

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

这篇关于将索引移动到新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆