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

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

问题描述

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

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

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

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