使用javascript单击列的标题对列升序和降序进行排序

时间:2014-10-14 03:19:31

标签: javascript sorting testcomplete

我需要帮助来创建一个javascript函数,允许我通过单击列标题对列(表)进行排序。该列包含8位数字和多行。我需要对它进行升序排序,然后通过验证降序,以确保排序确实有效,并记录每个排序。

我正在使用TestComplete和javascript脚本。

验证示例:

//验证排序功能

       for (var k = 0; i < records.length; k++)
        {
        if(column[k] != column_sorted[k])
        Log.Warning("Sort functionality does not work for the column")

        break;
       }
       Log.Checkpoint("Sort functionality works for the column")
         Log.Message(column_sorted[k].contentText);

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

简单的表格分类器并不难。诀窍是获得正确的排序功能,其余的是相当直接的。下面显示了如何使用一列数字对表格进行排序,以及为您添加多少功能。

一些测试HTML:

<table id="t0">
  <tr><td>44444444
  <tr><td>66666666
  <tr><td>33333333
  <tr><td>77777777
  <tr><td>11111111
  <tr><td>55555555
  <tr><td>22222222
</table>

<button onclick="sortRows(document.getElementById('t0'));">Sort</button>
<button onclick="sortRows(document.getElementById('t0'), true);">Sort reverse</button>

和脚本

// Sort table rows by the first cell (index 0)
// Setting reverse to true sorts in reverse
function sortRows(table, reverse) {

  // Get the rows, this gets all rows in a table but can be
  // restricted to those within a table section
  var row, rows = table.rows;
  var cells = [];
  reverse = !!reverse;

  // Get cells to sort and load into array
  // Gets the first cell in each row, but could use the cell index
  // of a header cell that was clicked on
  for (var i=0, iLen=rows.length; i<iLen; i++) {
    cells.push(rows[i].cells[0]);
  }

  // Sort the cells as numbers
  // or any other sort algorithm (e.g. date, alphabetic, etc.)
  cells.sort(function(a, b) {
    return getText(a) - getText(b);
  });

  // Reverse if required
  if (reverse) cells.reverse();

  // Order rows based on new order of cells
  // This works within a table section, making it easy to exclude
  // header and footer rows
  for (var j=0, jLen=cells.length; j<jLen; j++) {
    row = cells[j].parentNode;
    row.parentNode.appendChild(row);
  }
}

// A simple helper as textContent is not supported by all browsers in use
// Can be much more sophisticated and trim whitespace
function getText(el) {
  return el.textContent || el.innerText || '';
}

答案 1 :(得分:0)

这是一项艰巨的任务。您可能希望使用库,例如​​TableSorter:http://tablesorter.com/docs/#Demo

答案 2 :(得分:0)

如果已经将列的值放入数组,则可以使用JScript sort方法对此数组进行升序排序。如果需要执行降序排序,则需要使用简单的自定义排序功能。

function test()
{
  var records = new Array();
  records.push(92749283);
  records.push(47932729);
  records.push(12309334);
  records.push(84932889);

  Log.Message("Ascending");
  records.sort();
  for (var i = 0; i < records.length; i++)
    Log.Message(records[i]);

  Log.Message("Descending");
  records.sort(sortDesc);
  for (var i = 0; i < records.length; i++)
    Log.Message(records[i]);
}

function sortDesc(a, b)
{
  if (a > b) return -1;
  if (a < b) return 1;
  return 0;
}