Ask a newbie question, why does this table sorting output so many things when I click on name in line 123? Shouldn't it be output 5 times? Why is it 15 times? Where did I go wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表格排序</title>
<style>
* {
margin: 0;
padding: 0;
}
table {
width: 700px;
text-align: center;
margin: 100px auto;
border-radius: 10px;
padding: 10px;
box-shadow: 0 0 10px darkgreen;
font-size: 20px;
}
table caption {
line-height: 50px;
font-size: 30px;
font-weight: 700;
}
table thead {
height: 40px;
line-height: 40px;
background: darkgreen;
color: #ffffff;
}
table thead tr {
-webkit-user-select: none;
}
table thead tr th.cursor {
cursor: pointer;
}
table tbody tr {
height: 40px;
line-height: 40px;
}
table tbody tr.bg0 {
background: lightcyan;
}
table tbody tr.bg1 {
background: lightpink;
}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="0" id="tab">
<caption>表格排序</caption>
<thead>
<tr>
<th class="cursor">name</th>
<th class="cursor">age</th>
<th class="cursor">level</th>
<th>sex</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="../utils.js"></script>
<!--<script src="js/tab1.js"></script>-->
</body>
</html>
<script>
var oTab = document.getElementById("tab");
var tHead = oTab.tHead;
var tBody = oTab.tBodies[0];
var aCells = tHead.rows[0].cells;
var aRows = tBody.rows;
var data = null;
getData();
function getData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
data = utils.jsonParse(xhr.responseText);
bindData();
}
}
}
function bindData() {
var str = '';
for (var i = 0; i < data.length; i++) {
data[i].sex = data[i].sex == 0 ? "男" : "女";
str += '<tr>\
<td>' + data[i].name + '</td>\
<td>' + data[i].age + '</td>\
<td>' + data[i].level + '</td>\
<td>' + data[i].sex + '</td>\
</tr>'
}
tBody.innerHTML = str;
changeColor();
}
function changeColor() {
for (var i=0;i<aRows.length;i++){
aRows[i].className='bg'+i%2;
}
}
for (var i=0;i<aCells.length;i++){
aCells[i].index=i;
aCells[i].onclick=function () {
sort(this.index);
}
}
function sort(index) {
var ary=utils.makeArray(aRows);
ary.sort(function (a, b) {
console.log(a,b);
a=a.cells[index].innerHTML;
b=b.cells[index].innerHTML;
if(isNaN(a)||isNaN(b)){
return b.localeCompare(a);
}
return a-b;
});
var frg=document.createDocumentFragment();
for (var j=0;j<ary.length;j++){
frg.appendChild(ary[j]);
}
console.dir(ary);
tBody.appendChild(frg);
changeColor();
}
</script>
I understand, yes, that’s it