bootstrap表格时间排序
时间: 2023-12-09 13:01:14 浏览: 190
可以使用JavaScript对表格进行排序,具体步骤如下:
1. 给表格的时间列添加一个自定义的属性,例如data-time,表示该单元格中的时间值。
```html
<table id="myTable">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th data-time>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td data-time="2021-10-01T12:30:00">Oct 1, 2021 12:30 PM</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td data-time="2021-10-02T09:45:00">Oct 2, 2021 9:45 AM</td>
</tr>
<tr>
<td>3</td>
<td>Bob</td>
<td data-time="2021-10-03T15:20:00">Oct 3, 2021 3:20 PM</td>
</tr>
</tbody>
</table>
```
2. 使用JavaScript获取表格元素及其内容,并将其存储为数组。
```javascript
var table = document.getElementById('myTable');
var rows = table.getElementsByTagName('tr');
var data = [];
for (var i = 1; i < rows.length; i++) {
var row = rows[i];
var cells = row.getElementsByTagName('td');
var time = cells[2].getAttribute('data-time');
data.push({row: row, time: time});
}
```
3. 使用JavaScript的sort()方法对数组进行排序。
```javascript
data.sort(function(a, b) {
return new Date(a.time) - new Date(b.time);
});
```
4. 使用JavaScript将排好序的数据重新插入表格中。
```javascript
for (var i = 0; i < data.length; i++) {
table.appendChild(data[i].row);
}
```
完整代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Table Sort Time</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
function sortTable() {
var table = document.getElementById('myTable');
var rows = table.getElementsByTagName('tr');
var data = [];
for (var i = 1; i < rows.length; i++) {
var row = rows[i];
var cells = row.getElementsByTagName('td');
var time = cells[2].getAttribute('data-time');
data.push({row: row, time: time});
}
data.sort(function(a, b) {
return new Date(a.time) - new Date(b.time);
});
for (var i = 0; i < data.length; i++) {
table.appendChild(data[i].row);
}
}
</script>
</head>
<body>
<div class="container">
<h2>Bootstrap Table Sort Time</h2>
<p>Click the button to sort the table by time:</p>
<button onclick="sortTable()">Sort</button>
<table id="myTable" class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th data-time>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td data-time="2021-10-01T12:30:00">Oct 1, 2021 12:30 PM</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td data-time="2021-10-02T09:45:00">Oct 2, 2021 9:45 AM</td>
</tr>
<tr>
<td>3</td>
<td>Bob</td>
<td data-time="2021-10-03T15:20:00">Oct 3, 2021 3:20 PM</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
```
阅读全文