Created
July 6, 2019 13:14
-
-
Save Lodo4ka/78e8bd9b606e56c83c5f6b2bea2791aa to your computer and use it in GitHub Desktop.
sort table by javascritp with number and characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<style> | |
th { | |
cursor: pointer; | |
} | |
th:hover { | |
background: yellow; | |
} | |
</style> | |
</head> | |
<body> | |
<table id="grid"> | |
<thead> | |
<tr> | |
<th data-type="number">Возраст</th> | |
<th data-type="string">Имя</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td>5</td> | |
<td>Вася</td> | |
</tr> | |
<tr> | |
<td>2</td> | |
<td>Петя</td> | |
</tr> | |
<tr> | |
<td>12</td> | |
<td>Женя</td> | |
</tr> | |
<tr> | |
<td>9</td> | |
<td>Маша</td> | |
</tr> | |
<tr> | |
<td>1</td> | |
<td>Илья</td> | |
</tr> | |
</tbody> | |
</table> | |
<script> | |
/* ваш код */ | |
var grid = document.getElementById('grid'); | |
let flagNumber = false; | |
const sortColumn = (colNum, type) => { | |
let tdbody = document.querySelector("tbody"); | |
const rowsArr = tdbody.querySelectorAll("tr"); | |
let result; | |
if (type === "number" && !flagNumber) { | |
result = Array.from(rowsArr).sort((a, b) => { | |
return a.cells[colNum].innerHTML - b.cells[colNum].innerHTML; | |
}) | |
flagNumber = !flagNumber; | |
} else if (type === "number" && flagNumber) { | |
result = Array.from(rowsArr).sort((a, b) => { | |
return b.cells[colNum].innerHTML - a.cells[colNum].innerHTML | |
}) | |
flagNumber = !flagNumber; | |
} else if (type === "string") { | |
result = Array.from(rowsArr).sort((a, b) => { | |
return a.cells[colNum].innerHTML > b.cells[colNum].innerHTML; | |
}) | |
} | |
grid.removeChild(tdbody); | |
const newTbody = document.createElement("tbody"); | |
grid.appendChild(newTbody); | |
result.forEach(res => newTbody.appendChild(res)); | |
} | |
const thead = document.querySelector("thead"); | |
thead.onclick = (event) => { | |
sortColumn(event.target.cellIndex, event.target.dataset.type); | |
} | |
</script> | |
</body> | |
</htm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment