如何从下拉列表中对表进行排序

时间:2016-12-17 07:46:15

标签: javascript jquery html sorting dropdown

如何为此创建简单的排序功能。我知道有像tablesorter这样的插件。但它不会从下拉列表中对其进行排序。或者是否可以修改插件,以便它可以从下拉列表中进行排序。提前谢谢。

HTML:

<form action="#" method="post">
  <input type="text" id="UserID" name="UserID" readonly="readonly">
  <input type="text" id="UserName" name="UserName" placeholder="Name">
  <input type="text" id="UserOccupation" name="UserOccupation" placeholder="Occupation">
  <button type="button" name="button">Add</button><br>
</form>
Sort By:
<select>
  <option>ID</option>
  <option>Name</option>
  <option>Occupation</option>
</select>
<table id="table" class="tablesorter">
  <thead>
    <tr >
      <th>ID</th>
      <th>Name</th>
      <th>Occupation</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

使用Javascript:

$(document).ready(function() {
  //Set id field to 1
  var id = $('#UserID');
  id.val("1");

  //Add 1 to the id in textbox
  function incID(){
    var str = id.val();
    var int = parseInt(str);
    var idVal = int + 1;
    id.val(idVal.toString());
  }
  //When button clicked
  $('button').on('click', function(){
    //create a new object
    var obj = new Object();
    //pass value dynamically from input box
    obj.id = $('#UserID').val();
    obj.name = $('#UserName').val();
    obj.occupation = $("#UserOccupation").val();
    //display data to the table
    var addrow = "<tr><td>" + obj.id + "</td><td>" + obj.name + "</td><td>"+ obj.occupation +"</td></tr>";
    $("table tbody").append(addrow);
    //Add 1 to id field
    incID();
  });

});

1 个答案:

答案 0 :(得分:0)

对表进行排序非常容易,您需要做的就是使用javascript排序方法(http://www.w3schools.com/jsref/jsref_sort.asp)对行进行排序,然后将行重新添加到表中

您可以为不同的数据类型创建排序方法,例如:

function sortByNumber(rows, selector, ascending) {
  rows.sort(function(a, b) {
    var numberA = parseInt($(selector, a).text(), 10);
    var numberB = parseInt($(selector, b).text(), 10);

    if (ascending)
      return numberA - numberB;
    else
      return numberB - numberA;
  });

  return rows;
}

function sortByText(rows, selector, ascending) {
  rows.sort(function(a, b) {
    var textA = $(selector, a).text();
    var textB = $(selector, b).text();

    if (ascending)
      return textA.localeCompare(textB);
    else
      return textB.localeCompare(textA);
  });

  return rows;
}

https://jsfiddle.net/kg000ta7/处的工作示例)

但是,如果您计划在表中包含大量行或列,那么像tablesorter这样的插件可能会表现得更好。

根据文档,您可以通过触发“排序”手动对表格输入进行排序。事件:http://tablesorter.com/docs/example-trigger-sort.html

$('select').on('change', function() {
  var sorting;

  switch (field) {
    case 'ID':
      sorting = [[0,0]];
      break;
    case 'Name':
      sorting = [[1,0]];
      break;
    case 'Occupation':
      sorting = [[2,0]];
      break;
    default:
      console.error('Undefined sort field ' + field);
      break;
  }

  $("table").trigger("sorton",[sorting]); 
  return false; 
});