对html动态表进行排序,搜索和分页

时间:2016-03-21 07:20:29

标签: jquery html html-table



$(document).ready(function() {
  var user = {
    Id: '',
    Name: ''
  }

  var td = "";
  var row = "";
  $("#Add").click(function() {
    var userList = [];
    user.Id = $("#id").val();
    user.Name = $("#Name").val();

    userList.push(user);

    userList.forEach(function(u) {
      row += "<td>" + u.Id + "</td>"
      row += "<td>" + u.Name + "</td>"
    });

    var tr = "<tr>" + row + "</tr>";
    $("#reservations").append(tr);
    tr = " ";
    row = " ";
  });
});
&#13;
<style> th,
td {
  border: 1px solid black;
}
</style>
&#13;
<!DOCTYPE html>
<html>

<head>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js">
  </script>
</head>

<body>
  <input type="text" id="id" />
  <input type="text" id="Name" />
  <input type="button" id="Add" value="Add" />
  <br />
  <input type="button" id="sort" value="sort" />

  <table id="reservations">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</body>

</html>
&#13;
&#13;
&#13;

我创建了一个动态的html表。在该表中,我动态地添加行和数据。我使用了两个文本框和一个添加按钮。我所要做的就是将数据输入文本框并按“添加”按钮,仅使用JQuery将数据添加到表中。检查我的共享代码段。我需要启用对此代码的数据排序和搜索。

1 个答案:

答案 0 :(得分:0)

您在该代码中存在一些混淆,请检查并仔细查看差异:

$(document).ready(function() {
    var userList = [];
    $("#add").on('click', function() {
      var user = { //you need to create a new one each time
        Id: '',
        Name: ''
      }
      var row = $('<tr/>'); //you need to create a new one each time
      user.Id = $("#id").val();
      user.Name = $("#Name").val();

      userList.push(user); //I don't know what you want to do with this, but here you have a list of all added users

      row.append($('<td/>').text(user.Id)); //add text to TD and append TD to TR
      row.append($('<td/>').text(user.Name));

      $("#reservations").append(row); //append TR (with all TDs) to the TABLE
    });
});

检查fiddle

来自here的函数sortTable()

PS我建议你不要在DOM ID或类中使用大写字母