【问题标题】:Append a row to a sorted table with jQuery使用 jQuery 在排序表中追加一行
【发布时间】:2017-07-01 21:45:47
【问题描述】:

如何在动态生成的表中添加一行,但 tr 的 id 是按数字顺序排列的?

例如:

<table id="myDataTable">
<tr id="5143">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5144">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5149">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
<tr id="5150">
 <td>Data Cell 1</td>
 <td>Data Cell 2</td>
</tr>
</table>

如何添加一个 id 为 5145 的 tr,使其低于 5143 但高于 5149?如果可能的话,我想要一个不涉及插件的解决方案

【问题讨论】:

    标签: jquery html-table tablesorter


    【解决方案1】:

    我会对其进行排序...但是如果这有效与否,请确认

    //arr is an array of the row id's
    //row is the row being inserted
    idx = arr.sort().indexOf(row.id) - 1;
    $(row).insertAfter($("#myDataTable tr")[idx]) 
    

    例如

    http://jsfiddle.net/Dq37V/

    【讨论】:

    • 这确实有效,谢谢约瑟夫!另一个版本包含 Orolo 的方法不适用的场景:jsfiddle.net/Dq37V/1
    【解决方案2】:

    您可以遍历 tr 并进行比较;如果大于当前id,则添加。

    例子:

    $('#myDataTable tr').each(function(index, Element) {
        if (5145 > Number($(Element).attr('id'))) {
            $(Element).after('<tr id="5145"><td>Data Cell 1</td></tr>');
        }
    });
    

    【讨论】:

    • 我知道。假如。谢谢詹姆斯。
    • 谢谢奥罗洛!如果列表中存在 5144,此方法不会在 5144 上方和 5143 下方插入行,从而使列表不正确.. 5143 .. 5145 .. 5144?我修改了答案以适应这种情况
    【解决方案3】:

    您可以使用$('#myDataTable tr').each(function() { .. } 为了通过表的 tr 然后如果你发现匹配只是在函数之后使用 jquery 在右 tr 之后添加新行 `

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2021-12-20
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多