Не работает скрипт js для таблицы, которая выводится средством php
Код js, который должен сортировать данные на клиентской части
document.addEventListener('DOMContentLoaded', () => {
const getSort = ({ target }) => {
const order = (target.dataset.order = -(target.dataset.order || -1));
const index = [...target.parentNode.cells].indexOf(target);
const collator = new Intl.Collator(['en', 'ru'], { numeric: true });
const comparator = (index, order) => (a, b) => order * collator.compare(
a.children[index].innerHTML,
b.children[index].innerHTML
);
for(const tBody of target.closest('table').tBodies)
tBody.append(...[...tBody.rows].sort(comparator(index, order)));
for(const cell of target.parentNode.cells)
cell.classList.toggle('sorted', cell === target);
};
document.querySelectorAll('.table_sort thead').forEach(tableTH => tableTH.addEventListener('click', () => getSort(event)));
});
Код index.php (таблицу переписал в html чтобы не мозолить глаз ненужной информацией) c этой таблицей работает
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script src="script.js"></script>
</head>
<body>
<table class="table_sort">
<thead><tr>
<th>id</th>
<th>name</th>
<th>city</th>
<th>car</th>
</tr>
</thead>"
<tbody>
<tr>
<td>
1
</td>
<td>
Григорий
</td>
<td>
Москва
</td>
<td>
Porsche 911
</td>
</tr>
<tr>
<td>
2
</td>
<td>
Александр
</td>
<td>
Пермь
</td>
<td>
Subaru Impreza
</td>
</tr>
</tbody>
</table>
</body>
</html>
Как только вывожу таблицу средствами php, работать отказывается
<?php
$dataCars = file_get_contents("data_cars.json");
$decodeCars = json_decode($dataCars, true); //декодированный массив таблицы
$arrayCountCars = count($decodeCars); //кол-во участников
$parentKeyCars = array_keys(json_decode($dataCars, true)); //ключ родительского класса
$dataAttempts = file_get_contents("data_attempts.json");
$decodeAttempts = json_decode($dataAttempts, true); //декодированный массив таблицы
$arrayCountAttempts = count($decodeAttempts); //кол-во заездов
$parentKeyAttempts = array_keys(json_decode($dataAttempts, true)); //ключ родительского класса
$arraySort = array();
$bigData = array('id'=>"", 'name'=>"", 'resultData'=>"", 'sumResultData'=>"");
$bigDataName = array($bigData["name"]);
$bigDataResult = array($bigData["resultData"]);
$bigDataSum = array($bigData["sumResultData"]);
$bigDataId = array($bigData["id"]);
$i = 0; //кол-во заездов
$countAttempts = 0;
echo "<h2>Реультаты</h2>";
for ($j=0; $j < $arrayCountAttempts; $j++) {
$childArrayAttempts = $decodeAttempts[$parentKeyAttempts[$j]];
if ($childArrayAttempts["id"] == $parentKeyAttempts[$i+1]) {
$countAttempts += 1;
}
}
echo "<table class=\"table_sort\">";
echo "<thead><tr>
<th>id</th>
<th>Участник</th>";
for ($i=0; $i < $countAttempts; $i++) {
echo "<th>Заезд №";
echo $i + 1;
echo "</th>";
}
echo "<th>Сумма очков</th>";
echo "</tr></thead>";
for ($i=0; $i < $arrayCountCars; $i++) {
$sumResult = 0;
$childArrayCars = $decodeCars[$parentKeyCars[$i]];
$bigDataId[] = $childArrayCars["id"];
$bigDataName[] = $childArrayCars["name"];
for ($j=0; $j < $arrayCountAttempts; $j++) {
$childArrayAttempts = $decodeAttempts[$parentKeyAttempts[$j]];
if ($childArrayAttempts["id"] == $parentKeyAttempts[$i+1]) {
$sumResult += $childArrayAttempts["result"]; //сумма очков
$bigDataResult[] = $childArrayAttempts["result"];
}
}
$bigDataSum[] = $sumResult;
}
$t = 1;
for ($n=1; $n < $arrayCountCars + 1 ; $n++) {
$j = 0;
echo "<tbody><tr>";
echo "<td>$bigDataId[$n]</td>";
echo "<td>$bigDataName[$n]</td>";
while ($j < $countAttempts) {
echo "<td>$bigDataResult[$t]</td>";
$j++;
$t++;
}
echo "<td>$bigDataSum[$n]</td>";
echo "</tr></tbody>";
}
echo "</table>";
?>
Код css
<style>.table_sort table {
border-collapse: collapse;
}
body {
margin: 0px;
padding: 0px;
}
h2 {
color: #ffebcd;
background: #008b8b;
text-align: center;
margin: 0px;
margin-top: 2px;
margin-right: 2px;
margin-left: 2px;
padding: 0px;
border: 2px solid #846868;
}
table {
width: 100%;
}
.table_sort th {
color: #ffebcd;
background: #008b8b;
cursor: pointer;
}
.table_sort td,
.table_sort th {
width: 150px;
height: 40px;
text-align: center;
border: 2px solid #846868;
}
.table_sort tbody:nth-child(even) {
background: #e3e3e3;
}
th.sorted[data-order=\"1\"],
th.sorted[data-order=\"-1\"] {
position: relative;
}
th.sorted[data-order=\"1\"]::after,
th.sorted[data-order=\"-1\"]::after {
right: 8px;
position: absolute;
}
th.sorted[data-order=\"-1\"]::after {
content: \"▼\"
}
th.sorted[data-order=\"1\"]::after {
content: \"▲\"
}</style>
Ответы (1 шт):
Автор решения: NIKKIT
→ Ссылка
Все как всегда проще, тег tbody был внутри цикла и повторялся раз за разом.