微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数据表在特定索引下添加行

如何解决数据表在特定索引下添加行

使用数据表,以创建一个addRowBelowIndex()函数。我的大脑对此非常困惑,因为我不太确定如何处理它们的索引。

我正在研究5年前发现的解决方案:http://jsfiddle.net/mLh08nyg/

$("#example").on('click','tbody tr',function() {
var currentPage = table.page();

//insert a test row
count++;
table.row.add([count,count,count]).draw();

//move added row to desired index (here the row we clicked on)
var index = table.row(this).index(),rowCount = table.data().length-1,insertedRow = table.row(rowCount).data(),tempRow;

for (var i=rowCount;i>index;i--) {
    tempRow = table.row(i-1).data();
    table.row(i).data(tempRow);
    table.row(i-1).data(insertedRow);
}     
//refresh the page
table.page(currentPage).draw(false);
});  

在特定索引上方添加了新行,但是将算术更改为我认为应如何工作却无法正常工作,因此我显然不了解核心概念。

什么是最好的方法

谢谢。

解决方法

这是可疑行:

for (var i=rowCount;i>index;i--)

更改为

for (var i=rowCount;i>index+1;i--)

使其执行所需的行为。工作小提琴here

那为什么行得通?本质上,代码执行的是一系列交换,从表的最后一个条目(索引为rowCount的表行)开始,我们在其中插入新行,并在我们单击的行(索引为index的表行)处结束。请注意,index是使用table.row(this).index()计算的,其中this是触发click事件侦听器的DOM元素。

在每次交换中,我们将新插入的行与其正上方的行交换。

因此,在循环的第一次迭代中,我们从最后一行开始,这就是我们明确要做的事情。

tempRow = table.row(i-1).data(); // Save the second to last row to a temporary variable
table.row(i).data(tempRow); // Set the last row to the temporary variable
table.row(i-1).data(insertedRow); // Set the second to the last row as our inserted row

第一次迭代后,我们从此更改了表的结尾:

...
original 3rd to last row
original 2nd to last row
original last row
>newly inserted row<

对此:

...
original 3rd to last row
original 2nd to last row
>newly inserted row<        << swapped
original last row           << swapped

因此,我们继续在行ii-1上执行此交换,直到我们新创建的行到达我们单击的行为止。在原始代码中,我们的最后一次迭代是iindex大1时。因此,该迭代中的i-1是我们单击的行的位置。由于我们将插入的行与i-1上的原始行交换,因此新行将插入到我们单击的行上方。要在点击的行下方插入新行,我们可以提前一个迭代结束此循环,因此我们永远不会将新行与原始点击的行交换。

请注意,对于任何类型的排序,此方法均不起作用,因为一旦插入行,行将自动排序,因此交换将无法按预期进行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。