- 请完成 sortData 函数,根据参数的要求对表格所有行进行重新排序。
1、type为product、price或者sales,分别对应第1 ~ 3列
2、order为asc或者desc,asc表示升序,desc为降序
3、例如 sortData(‘price’, ‘asc’) 表示按照price列从低到高排序
4、所有表格内容均为数字,每一列数字均不会重复
5、不要使用第三方插件
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body,
html {
padding: 0;
margin: 0;
font-size: 14px;
color: #000000;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
thead {
background: #3d444c;
color: #ffffff;
}
td,
th {
border: 1px solid #e1e1e1;
padding: 0;
height: 30px;
line-height: 30px;
text-align: center;
}
.sort-asc::after,
.sort-desc::after {
content: ' ';
display: inline-block;
margin-left: 5px;
vertical-align: middle;
}
.sort-asc::after {
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-bottom: 4px solid #eee;
}
.sort-desc::after {
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid #eee;
}
</style>
</head>
<body>
<table>
<thead id="jsHeader">
<tr>
<th id="product">product</th>
<th id="price">price</th>
<th id="sales">sales</th>
</tr>
</thead>
<tbody id="jsList">
<tr>
<td>1</td>
<td>10.0</td>
<td>800</td>
</tr>
<tr>
<td>2</td>
<td>30.0</td>
<td>300</td>
</tr>
<tr>
<td>3</td>
<td>20.5</td>
<td>100</td>
</tr>
<tr>
<td>4</td>
<td>40.5</td>
<td>200</td>
</tr>
<tr>
<td>5</td>
<td>60.5</td>
<td>600</td>
</tr>
<tr>
<td>6</td>
<td>50.0</td>
<td>400</td>
</tr>
<tr>
<td>7</td>
<td>70.0</td>
<td>700</td>
</tr>
<tr>
<td>8</td>
<td>80.5</td>
<td>500</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
var oThead = document.querySelector('#jsHeader');
var oTbody = document.querySelector('#jsList');
var oTr = document.querySelectorAll('#jsList tr');
var oProduct = document.querySelector('#product');
var oPrice = document.querySelector('#price');
var oSales = document.querySelector('#sales');
function sortData(type, order) {
var status = 1;
if (type == 'product') {
var i = 0;
} else if (type == 'price') {
var i = 1;
} else if (type == 'sales') {
var i = 2;
}
if (order == 'asc') {
var status = -1;
} else {
var status = 1;
}
var books = [];
oTr.forEach(function(element) {
books.push(element);
});
books.sort(function(elementA, elementB) {
var targetA = elementA.children[i].innerText;
var targetB = elementB.children[i].innerText;
return (targetB - targetA) * status;
})
books.forEach(function(element) {
oTbody.appendChild(element);
})
}
sortData('price', 'desc');
</script>
</body>
</html>