【问题标题】:Sort Table after Append jQuery/ Javascript追加 jQuery/Javascript 后排序表
【发布时间】:2021-12-20 14:08:33
【问题描述】:

下面是我的代码,当点击添加按钮到我的表格时,我的问题是,有没有办法在table.append 之后根据ItemId 对表格进行排序?

    var ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    ItemId +
    "</td><td id='ItemCodeEdit'>" +
    ItemCode +
    "</td><td style='text-align: right'>" +

    parseFloat(Quantity).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    ItemUOM +
    "</td><td hidden>" +
    LocationId +
    "</td><td>" +
    LocationCode +
    "</td><td style='text-align: right'>" +
    UnitCostParse +
    "</td><td style='text-align: right' >" +

    Total2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.append(ItemList);

编辑,请看下面我想要实现的截图: 我希望我的表格按突出显示的列排序,他们有什么方法可以在单击添加/编辑后对整个表格进行排序?

【问题讨论】:

标签: javascript jquery sorting append


【解决方案1】:

感谢您的 cmets,我能够通过在附加的末尾添加一个排序函数来解决这个问题。

请在下面找到我的代码,我在追加后调用了这个函数。

function sortTable() {
        var table, rows, switching, i, x, y, shouldSwitch;
        table = document.getElementById("tblItemList");
        switching = true;
        /*Make a loop that will continue until
        no switching has been done:*/
        while (switching) {
            //start by saying: no switching is done:
            switching = false;
            rows = table.rows;
            /*Loop through all table rows (except the
            first, which contains table headers):*/
            for (i = 1; i < (rows.length - 1); i++) {
                //start by saying there should be no switching:
                shouldSwitch = false;
                /*Get the two elements you want to compare,
                one from current row and one from the next:*/
                x = rows[i].getElementsByTagName("TD")[8];
                y = rows[i + 1].getElementsByTagName("TD")[8];

                var cmpX = isNaN(parseInt(x.innerHTML)) ? x.innerHTML.toLowerCase() : parseInt(x.innerHTML);
                var cmpY = isNaN(parseInt(y.innerHTML)) ? y.innerHTML.toLowerCase() : parseInt(y.innerHTML);
                cmpX = (cmpX == '-') ? 0 : cmpX;
                cmpY = (cmpY == '-') ? 0 : cmpY;
                //check if the two rows should switch place:
                if (cmpX > cmpY) {
                    //if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }
            if (shouldSwitch) {
                /*If a switch has been marked, make the switch
                and mark that a switch has been done:*/
                rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                switching = true;
            }
        }
    }

【讨论】:

  • 此功能有效,但应改进。永远不要在外面使用循环变量(这是不好的做法)。您应该强制在内部声明变量以避免此错误(for (let i = 1; . . .,然后您可以将if (shouldSwitch) {. . .} 的代码移动到shouldSwitch = true; 的位置(并删除ìf` 和变量shouldSwitch)。另外现在,您可以删除break。其他情况是rows[i].getElementsByTagName("TD")[8] 应该是rows[i].children[8],因为如果您在此表内有一张表,则效果不佳
【解决方案2】:

在 jQuery 中,您可以通过 detachsortappend 重新排序元素。

正如其他答案中提到的,为元素提供相同的 ID 会导致问题,尽管您可以通过使用 classes 轻松解决此问题。

这里有一些示例代码:

$('button.add-item').on('click', function() {
  let item_id = (Math.random()+'').slice(-4);

  $('table').append(`
    <tr>
      <td class="item-id hidden">
        ${item_id}
      </td>
      <td class="item-code-edit">
        <input value="${item_id}" disabled>
      </td>
      <td class="item-cost align-right">
        ${parseFloat(Math.random() * 1000).toFixed(2)}
      </td>
      <td class="item-uofm">
        ItemUOM 
      </td>
      <td class="location-id hidden">
        LocationId
      </td>
      <td class="location-code">
        LocationCode
      </td>
      <td class="unit-cost-parse align-right">
        UnitCostParse
      </td>
      <td class="total align-right">
        Total2
      </td>
      <td>
        <div class="buttons">
          <button class="edit-item btn btn-default btn-xs glyphicon glyphicon-edit">EDIT</button>
          <button class="remove-item btn btn-default btn-xs glyphicon glyphicon-trash">REMOVE</button>
        </div>
      </td>
   </tr>`);
   
   //this is the code that does the re-ordering
   $('table').append($('table').find('tr').detach().sort((a, b) =>
     $(a).find('.item-id').text() - $(b).find('.item-id').text()));
 });
 
 $('table')
   .on('click', 'button.edit-item', function() {
     let $id_input = $(this).parents('tr').find('.item-code-edit input');
     $id_input.prop('disabled', !$id_input.prop('disabled'));
   })
   .on('click', 'button.remove-item', function() {
     $(this).parents('tr').remove();
 });
.align-right{
  text-align: right;}

.hidden{
  display: none;}
  
.item-code-edit input{
  width: 40px;}

table td{
  min-width: 64px;}
<button class="add-item">ADD ITEM</button>
<table></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【讨论】:

  • 您好,谢谢您,我按照您的代码重新排序,但是单击按钮后,表格完全消失(/分离)。我正在进一步检查这对我来说是如何工作的
【解决方案3】:

由于您附加到名为 tblItemList 的内容,我假设您想要对数据结构而不是实际元素进行排序。

    let tblItemList = [];
    var ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    2 +
    "</td><td id='ItemCodeEdit'>" +
    2 +
    "</td><td style='text-align: right'>" +

    parseFloat(2).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    2 +
    "</td><td hidden>" +
    2 +
    "</td><td>" +
    2 +
    "</td><td style='text-align: right'>" +
    2 +
    "</td><td style='text-align: right' >" +

    2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.push(ItemList);
    ItemList = "<tr><td hidden id='ItemIdEdit'>" +
    1 +
    "</td><td id='ItemCodeEdit'>" +
    2 +
    "</td><td style='text-align: right'>" +

    parseFloat(2).toFixed(2) +
    "</td><td id='ItemUOM2'>" +


    2 +
    "</td><td hidden>" +
    2 +
    "</td><td>" +
    2 +
    "</td><td style='text-align: right'>" +
    2 +
    "</td><td style='text-align: right' >" +

    2 +
    "</td><td><div class='buttons'> <a href='#' class='btn btn-default btn-xs glyphicon glyphicon-edit' id='btnEdit'onclick='EditItem(this)'></div></td><td><div class='buttons'><a href='#' class='btn btn-default btn-xs glyphicon glyphicon-trash' id='btnAddToList'onclick='RemoveItem(this)'></a></div></td></tr>";

tblItemList.push(ItemList);
for (let i = 0; i < tblItemList.length; i++) {
    for (let j = i + 1; j < tblItemList.length; j++) {
        let itemI = parseInt($(tblItemList[i]).find("#ItemIdEdit").text());
        let itemJ = parseInt($(tblItemList[j]).find("#ItemIdEdit").text());
        if (itemI > itemJ) {
            let aux = tblItemList[i];
            tblItemList[i] = tblItemList[j];
            tblItemList[j] = aux;
        }
    }
}

console.log(tblItemList);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

请注意,您多次使用相同的id,这会导致 HTML 无效。虽然这个问题是可以解决的,但您可能也想解决它。

【讨论】:

  • .append() 是一个 DOM 函数,而不是一个数组函数,所以我不确定 OP 是否尝试构建数据结构,而只是尝试对一些 DOM 元素进行排序。此外,DOM 已经是一个可变变量,试图同时维护一个数组并使其与 DOM 保持同步可能最终会非常令人头疼。
  • @PoorlyWrittenCode OP 附加文本的事实让我认为它是问题中未定义的数据结构。
  • @PoorlyWrittenCode 但您可能是对的。如果操作员告诉我这是实际的 DOM 代码,那么我将删除我的答案。
【解决方案4】:

您可以使用appendprependafter方法移动节点。

https://developer.mozilla.org/en-US/docs/Web/API/Element/append

原版 javascript 的伪代码:

document.getElementById("yourTableIdOrTbody").append(document.getElementById("yourTrToMOveToTheEnd"));
document.getElementById("yourTableIdOrTbody").prepend(document.getElementById("yourTrToMOveToTheBegin"));
document.getElementById("trIdBase").after(document.getElementById("yourTrToMOveToAfterTrBase"));

对于 JQuery (https://api.jquery.com/after/):

$("#yourTableIdOrTbody").append($("#yourTrToMOveToTheEnd"));
$("#yourTableIdOrTbody").prepend($("#yourTrToMOveToTheBegin"));
$("#trIdBase").after($("#yourTrToMOveToAfterTrBase"));

当然,您不需要 id 来匹配节点。您可以使用任何其他方式搜索节点。

【讨论】:

  • 感谢您的提示,您知道我的表格将如何进行相应排序吗?
  • 如果你的表总是排序的,为了插入第一行,使用append函数而不是tabletbody。对于其他人,在插入下一行之前,您可以搜索最后一行节点 (tr),其中 itemId 小于您的 itemId,您可以在该节点上使用 after 函数
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2016-08-11
  • 2014-06-07
  • 1970-01-01
相关资源
最近更新 更多