При подгрузке древовидных комментариев при скролле дочерние комменты пропадают
есть рабочий код подгрузки древовидных комментариев при скролле на javascript. Дочерние комментарии отображаются как положено, только если нажать кнопку "Подгрузить еще" дочерние комментарии пропадают, так как теряется id комментария. Есть какие-нибудь предложения?
const citiesContainer = document.getElementById('cities');
const btnLoad = document.getElementById('load');
const loader = document.querySelector('.loader');
let page = 1;
let lock = false;
async function getCities() {
const res = await fetch(`index.php?page=${page}`);
return res.text();
}
// getCities();
async function showCities() {
const cities = await getCities();
if (cities) {
citiesContainer.insertAdjacentHTML('beforeend', cities);
lock = false;
} else {
btnLoad.classList.add('d-none');
lock = true;
}
}
loader.classList.add('show');
setTimeout(() => {
showCities();
loader.classList.remove('show');
}, 1000);
btnLoad.addEventListener('click', () => {
loader.classList.add('show');
setTimeout(() => {
page++;
showCities();
loader.classList.remove('show');
}, 1000);
});
.loader {display: none;}
.loader img {width: 100px;}
.show {display: block;}
.answer_comment {margin-left: 2em}
<?php
require_once __DIR__ . '/db.php';
function get_start(int $page, int $per_page): int
{
return ($page - 1) * $per_page;
}
function get_cities(int $start, int $per_page): array
{
global $db;
$stmt = $db->prepare("SELECT * FROM city LIMIT $start, $per_page");
$stmt->execute();
return $stmt->fetchAll();
}
if (isset($_GET['page'])) {
$page = (int)$_GET['page'];
$per_page = 10;
$start = get_start($page, $per_page);
$cities = get_cities($start, $per_page);
$html = '';
if ($cities) {
$tree = array();
foreach ($cities as $Row) {
$Row['childs'] = array();
$tree[$Row['id']] = $Row;
}
foreach ($tree as $k => &$v) {
if ($v['parent_id'] != 0) {
$tree[$v['parent_id']]['childs'][] =& $v;
}
}
unset($v);
// удалить комментарии ребенка с верхнего уровня
foreach ($tree as $k => $v) {
if ($v['parent_id'] != 0) {
unset($tree[$k]);
}
}
// теперь мы выводим список комментариев, это базовая рекурсивная функция
function display_comments(array $tree, $level = 0) {
global $CONNECT;
foreach ($tree as $Row) {
if ($level) {
$answer_comment = 'answer_comment';
}
echo '
<li class="'.$answer_comment.'">'.$Row['name'].'('.$Row['id'].') - '.$Row['population'].'</li>';
if (!empty($Row['childs'])) {
display_comments($Row['childs'], $level + 1);
}
}
}
}
display_comments($tree);
die;
}
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="container-fluid mb-3">
<ul id="cities"></ul>
<div class="loader">
<img src="/images/img/loading-icon.gif" alt="">
</div>
<button class="btn btn-primary" id="load">Load more</button>
</div>
<footer style="background-color: #000; height: 200px; padding: 0;"></footer>