строка таблицы сортировки с использованием jquery - PullRequest
0 голосов
/ 08 мая 2020

Я хочу отсортировать строки таблицы в jquery, я пробовал несколько решений, но у меня несколько строк, поэтому сортировка работает неправильно, проверьте код ниже.

My HTML:

<table id="carrierGrid" class="czl_items-grid czl_grid-carrier">
                    <thead>
                        <tr>
                            <th class="sortable" onclick="sortTable(0,'discount',event)">Discount</th>
                            <th class="sortable" onclick="sortTable(1,'charge',event)">Surcharge</th>
                            <th class="sortable" onclick="sortTable(4,'total',event)">Total Price</th>
                            <th>&nbsp;</th>
                        </tr>
                    </thead>
                    <tbody id="summary">
                    <th:block th:each="word,itera : ${List}">
                            <tr th:id="'tbodyTemp-'+${itera.index}"></tr>
                                <td><input class="rater-results"  th:id="'discount-'+${itera.index}" name="discount" size="6" type="text" tabindex="-1" readonly></td>
                                <td><input class="rater-results" th:id="'charge-'+${itera.index}" name="charge" size="6" type="text" tabindex="-1" readonly></td>
                                <td><input class="rater-results" th:id="'charge-totals-'+${itera.index}" name="chargeTotal" size="8" type="text" tabindex="-1" readonly></td>
                            <td>
                                <a th:href="'javascript:toggle('+${itera.index}+')'" th:id="'grid-expansion-'+${itera.index}" class="grid-expansion-trigger">+</a>
                            </td>
                        <!-- EXPAND -->
                        <tr  style="display:none !important">
                            <td colspan="7">
                        <table class="grid-expansion-table">
                            <tr >
                                <td data-i18n="def">Def</td>
                            </tr>
                            <tr >
                                <td data-i18n="gross">Gross</td>
                            </tr>
                            <tr >
                                <td data-i18n="discount">Discount</td>
                            </tr>
                            <tr 
                                <td data-i18n="charge">charge</td>

                            </tr>
                            <tr style="display:none">
                                <td data-i18n="accessorial">Accessorial</td>

                            </tr>

                            <tr id="total-row">
                                <td data-i18n="net">Net</td>
                            </tr>
                            <tr id="currency-row">
                                <td colspan="3"></td>
                                <td id="currency" align="right"></td>
                            </tr>
                            <tr>
                                <td data-i18n="ttt">ttt</td>
                                <td>
                                    <input class="rater-rbno" th:id="'rbno-'+${itera.index}" name="rbno" size="8" type="text" readonly="" tabindex="-1">
                                </td>
                            </tr>
                        </table>
                            </td>
                        </tr>
                        <!-- END EXPAND -->
                    </th:block>
                    </tbody>
                </table>

Mt JQuery:

function sortTable(n,text, event) {

    // event.target.classList.add('headerSortUp')
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("carrierGrid");

    switching = true;
    rows = table.rows;
    console.log("rows data"+rows);
    if ((rows.length - 1)<=1) {
        switching = false;
        return;
    }

    // Set the sorting direction to ascending:
    dir = "asc";

    /*
     * Make a loop that will continue until no switching has been done:
     */
    while (switching) {
        // start by saying: no switching is done:

        switching = false;

        /*
         * Loop through all table rows (except the first, which contains table
         * headers):
         */
        for (i = 1; i < (rows.length - 1); i++) {
            // start by saying there should be no switching:
            shouldSwitch = false;
            /*
             * Get the two elements you want to compare, one from current row
             * and one from the next:
             */
            x = rows[i];
            y = rows[i + 3];
            /*
             * check if the two rows should switch place, based on the
             * direction, asc or desc:
             */

            var valOfX = x.dataset[text];
            var valOfY = y.dataset[text];

            /*if (n == 3) {
                valOfX = parseFloat(valOfX.replace(/[-[\]{}()*+?,\\^$|#\s]/g, ''));
                valOfY = parseFloat(valOfY.replace(/[-[\]{}()*+?,\\^$|#\s]/g, ''));
            }*/

            if(valOfX == "") {
                valOfX = 0;
            }

            if( valOfY == "") {
                valOfY = 0;
            }

            if(!isNaN(valOfX)) {
                valOfX=parseInt(valOfX);
                valOfY=parseInt(valOfY);
            }

            if (dir == "asc") {
                if (valOfX > valOfY) {
                    // if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "desc") {
                if (valOfX < valOfY) {
                    // if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }
        }

        if (shouldSwitch) {
            /*
             * If a switch has been marked, make the switch and mark that a
             * switch has been done:
             */
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            // Each time a switch is done, increase this count by 1:
            switchcount++;
        } else {
            /*
             * If no switching has been done AND the direction is "asc", set the
             * direction to "desc" and run the while loop again.
             */
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
    // Adding icons for up and down
    $('#carrierGrid th').removeClass('headerSortDown').removeClass('headerSortUp')
    $(event.target).addClass(dir == "asc" ? "headerSortDown" : "headerSortUp")
}

добавление dataSet:

$.each(outData, function( key, data ) {
    var html = '<tr id="dataSet-'+(key)+'" data-surcharge="' + data.surchargePercentUsed + '" data-discount="' + data.discountPercentage + '" data-total="' + data.totalCharge + '" style="display : none;"></tr>'
    $('#tbodyTemp-'+(key)).replaceWith(html);

при вызове функции sortTable мы будем читать значения dataSet и использовать insertBefore для замены. Но сортировка работает некорректно, откройте для любого решения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...