1

У меня есть таблица, в которой я вывожу данные с помощью Django template. Я нашел код JS для сортировки таблиц, но из-за того что у меня есть еще одна таблица в HTML внутри первой (которую можно увидеть при нажатии на <div class="col-12 text-center") сортирует именно вторую. Как ее исключить из сортировки? Как только удаляю из HTML "внутреннюю" таблицу все в порядке и сортировка отрабатывает как надо.

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const theads = document.querySelectorAll(".table thead");
        theads.forEach(thead => thead.addEventListener("click", evt => getSort(evt)));

        function getSort({ target }) {
            const order = (target.dataset.order = -(target.dataset.order || -1));
            const thList = Array.from(target.parentNode.cells);
            console.log(thList)
            const index = thList.indexOf(target);
            const collator = new Intl.Collator(["en", "ru"], { numeric: true });
            const comparator = (index, order) => (a, b) => {
                return (
                    order * // order - переключатель, для того чтобы менять порядок сортировки: "с начала" или "с конца"
                    collator.compare(a.children[index].textContent, b.children[index].textContent)
                );
            };
            const tablesBodies = Array.from(target.closest("table").tBodies);
            console.log(tablesBodies)
            tablesBodies.forEach(tBody => {
                tBody.append(...Array.from(tBody.rows).sort(comparator(index, order)));
            });
            thList.forEach( th => th.classList.toggle("sorted", th === target));
        }
    });
</script>
<style>
    th.sorted[data-order="-1"]::after {
        content: "▼"
    }

    th.sorted[data-order="1"]::after {
        content: "▲"
    }
</style>
<table class="table">
        <thead class="thead-dark">
        <tr>
            <th>#</th>
            <th>Договір<br>Тип</th>
            <th>Пот.<br>Пот</th>
            <th>Валюта</th>
            <th>Джерело</th>
            <th>Дата</th>
        </tr>
        </thead>
        <tbody id="tuda_stories" style="display:none;">
        {% for story in stories %}
        <tr style="background-color: #f5f5f5;">
            <td>{{forloop.counter}}</td>
            <td>{{story.dref}}<br>{{story.paw}}</td>
            <td>{{story.ref}}<br>{{story.daw}}</td>
            <td>{{story.curr}}<br>{{story.daw}}</td>
            <td>{{story.donor}}<br>{{story.last_story.status}}</td>
            <td>{{story.dat|date:"d.m.Y"}}</td>
        </tr>
            <td colspan="7" style="padding: 3px;">
                <div class="row">
                    <div class="col-12 text-center" onclick="toggleElement('history_' + {{story.id}})">
                            <span class="badge badge-secondary">&#8744;</span> История
                        <span class="badge badge-secondary">&#8744;</span>
                    </div>
                    <div class="col-12" style="display: none;" id="history_{{story.id}}">
                        <table class="table-sort table-warning">
                            <thead>
                                <tr>
                                    <th>Період</th>
                                    <th>Сума</th>
                                    <th>Ісп</th>
                                    <th>Сума за.</th>
                                    <th>Сума об.</th>
                                    <th>Термін проср.</th>
                                    <th>Сума проср.</th>
                                    <th>Кред. транш</th>
                                </tr>
                            </thead>
                            {% for history in dealhistory.all %}
                                <tr class="{% if history.dlamtexp %}table-danger{% elif history.pay == 'Да' %}table-success{% endif %}">
                                    <td>01.{{history.month}}.{{history.year}}</td>
                                    <td>{{history.lim}}</td>
                                    <td>{{history.pay}}</td>
                                    <td>{{history.amtpay}}</td>
                                    <td>{{history.day}}</td>
                                    <td>{{history.amte}}</td>
                                    <td>{{history.fluse}}</td>
                                </tr>
                            {% endfor %}
                        </table>
                    </div>
                </div>
            </td>
        {% endfor %}
        </tbody>
    </table>

Когда отрабатывет скрипт выпадает ошибка

введите сюда описание изображения

1 ответ 1

1

Вот решил залить на codeopen, чтобы более наглядно было видно в чем проблема.

// https://inter-net.pro/javascript/sort-table
// https://learn.javascript.ru/dom-navigation

// ParentNode.append
// https://developer.mozilla.org/ru/docs/Web/API/ParentNode/append

"use strict";
document.addEventListener('DOMContentLoaded', () => {
// Все таблицы в которых будет осуществлена сортировка по thead
        const theads = document.querySelectorAll(".table_sort thead");
        theads.forEach(thead => thead.addEventListener("click", evt => getSort(evt)));

        function getSort({ target }) {
          const order = (target.dataset.order = -(target.dataset.order || -1));
          const thList = Array.from(target.parentNode.cells);
          console.log(order)
          console.log(thList)
          console.log(target)
          const index = thList.indexOf(target);
          const collator = new Intl.Collator(["en", "ru"], { numeric: true });
          const comparator = (index, order) => (a, b) => {
            return (
              order * // order - переключатель, для того чтобы менять порядок сортировки: "с начала" или "с конца"
              collator.compare(a.children[index].textContent, b.children[index].textContent)
            );
          };
          console.log('HEre', target.closest("table").tBodies)
          const tablesBodies = Array.from(target.closest("table").tBodies);
          console.log(tablesBodies)
          tablesBodies.forEach(tBody => {
            tBody.append(...Array.from(tBody.rows).sort(comparator(index, order)));
          });
          thList.forEach( th => th.classList.toggle("sorted", th === target));
        }
});

https://codepen.io/dmitriyposypaiko/pen/XWpjdNK?editors=1000

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.