使用纯JavaScript并且没有任何库对表客户端进行排序

时间:2015-08-04 01:43:03

标签: javascript arrays sorting html-table

我在网站上搜索了很多,但我无法找到答案。它们太复杂了,或者它们需要JQuery,一个外部库或者我无法使它们工作。

我正在寻找具有以下条件的JavaScript。

  1. 从书签
  2. 在客户端运行
  3. 易于理解
  4. 没有图书馆
  5. 对html表和高光相关标题进行排序
  6. 该项目适用于帮助台软件,其中由于回复/转发/对话而创建了多个故障单。它变得如下(即):

    • 首票标题:无法登录
    • 第二张门票: Re:无法登录
    • 第三张门票: Fw:R:无法登录

    在30张或更多门票的中间找到并合并它们有​​时会包含错误和烦恼,尤其是在我忙的时候。所以我想要一种方法来点击并突出显示它们而不影响任何格式化。

    html表确实有一个头,但前两行有head和filtering函数。所以应该有一种方法可以跳过它们。

    请建议执行此操作的代码。

1 个答案:

答案 0 :(得分:1)

请注意,我是Java脚本的完全初学者,但能够一次构建此解决方案。

解决方案是逐行浏览表并提取" textContent"来自所需的单元格(行中的列)。并创建一个数组,其中第一个级别是清理后的单元格,然后第二个级别是行本身。

清除以通过删除" Re:"来检测相同的故障单标题和" Fw:"来自textContent

var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
key = key.replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();

在扣除startRow的同时创建数组,使其从0开始。

arr[i - startRow] = [key, rows[i]];

它会变成这样的arr [index] = [key,row]

arr[0] = ['Cannot login','<td>....</td>']
arr[1] = ['next subject','<td>....</td>']

然后我们可以使用简单的数组排序函数。

arr.sort();

之后我们可以删除当前表行,同时保留前两行。

    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };

然后我们可以重新生成表,同时检查任何重复项并将背景表更改为&#34;黄色&#34;重复。

完整的代码如下:

javascript :
sortandclean();
function sortandclean() {
    var col = 6; /* title row */
    var startRow = 2; /* to skip the first two rows */
    var arr = []; /* main array which will contains the rows */
    var tbody = document.getElementById('RequestsView_TABLE').tBodies[0];
    var rows = tbody.rows;
    for (i = startRow; i < rows.length; i++) {
        var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
        key = key .replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();
        arr[i - startRow] = [key, rows[i]];
    };
    console.log('rows: ' + rows.length);
    arr.sort(); /* sorting the easy way. works with both texts and numbers */
    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };
    for (i = 0; i < arr.length; i++) {
        rowToInsert = arr[i][1]; /* arr[i][0] has the key and arr[i][1] has the row */
        if (arr[i][0] == lastrow) {
            rowToInsert.cells[col].style.backgroundColor = "yellow";
            tbody.rows[tbody.rows.length - 1].cells[col].style.backgroundColor = "yellow";
        }; /* if the current row have the same clean title highlight both current and previous rows title cell */
        tbody.appendChild(rowToInsert);
        var lastrow = arr[i][0];
        totalRows = i;
    };
    console.log('rows reinserted: ' + (totalRows + 1));
} void(0);

使用块注释来注释代码,使其在书签中正常工作。 (即/ *一些评论* /)