Таблица сортировки jquery по содержимому столбца в ячейке - PullRequest
0 голосов
/ 04 ноября 2019

Я пытаюсь отсортировать таблицу по столбцам в соответствии с содержимым в первой строке 'tbody' (tr class = 'Statistics)'.

У каждого 'td' в строке есть два 'div', идентифицированных классами, которые соответствуют значениям для их соответствующего выбора в раскрывающемся списке сортировки. (для удобства обозначен цветом, как на рисунке ниже)

enter image description here

Jquery, который я использую для активации функции сортировки, выглядит следующим образом:

jQuery(document).ready(function ($) {

        $("#SortBy").on('change', function() {
            var Column = $(".CompTable tr > td:nth-child(n):not(:first-child), .CompTable tr > th:nth-child(n):not(:first-child)");

            Column.sort(function(a, b) {
                a = $(a).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
                b = $(b).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());

                return (a === 'NA')-(b === 'NA') || -(a>b)||+(a<b);
            })
            jQuery('.divResult').html(Column); // <-- Table nested inside 'div' 
        });
    });

Я полагаю, что проблема связана с этим битом кода, который я использую для идентификации каждого столбца, кроме 1-го, в таблице:

var Column = $(".CompTable tr > td:nth-child(n):not(:first-child), .CompTable tr > th:nth-child(n):not(:first-child)");

Пожалуйста, помогите мне исправить вышеприведенноекод. В настоящее время, когда я выбираю опцию сортировки, таблица исчезает. : /

Ниже приведен весь рабочий код для справки:

jQuery(document).ready(function ($) {

        $("#SortBy").on('change', function() {
        var Column = $(".CompTable tr > td:nth-child(n):not(:first-child), .CompTable tr > th:nth-child(n):not(:first-child)");
            
            Column.sort(function(a, b) {
                a = $(a).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
                b = $(b).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());

                return (a === 'NA')-(b === 'NA') || -(a>b)||+(a<b);
            })
            jQuery('.divResult').html(Column);
        });
    });
.CompTable {
  table-layout: fixed;
  width: 50%;
  position: relative;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div id="SortByDiv">
    Sort by: 
    <select id="SortBy">
        <option></option>
        <option value=Battery style="color: blue">Battery</option>
        <option value=ScreenSize style="color: red">ScreenSize</option>
    </select>
</br></br></br>
    <div class="divResult">
    <table class="CompTable">
    <thead>
        <th>&nbsp;</th>
        <th>Samsung</th>
        <th>Apple</th>
        <th>Motorola</th>
    </thead>
    <tbody>
        <tr class="Statistics">
            <td>Statistics</td>
            <td>
                <div style="display:flex; flex-flow:column-wrap; width: 100%;">
                    <div class="Battery" style="display:flex; color:blue; width: 100%;">3200</div>
                    <div class="ScreenSize" style="display:flex; color:red; width: 100%;">1024</div>
                </div>
            </td>
            <td>
                <div style="display:flex; flex-flow:column-wrap; width: 100%;">
                    <div class="Battery" style="display:flex; color:blue; width: 100%;">NA</div>
                    <div class="ScreenSize" style="display:flex; color:red; width: 100%;">1900</div>
                </div>
            </td>
            <td>
                <div style="display:flex; flex-flow:column-wrap; width: 100%;">
                    <div class="Battery" style="display:flex; color:blue; width: 100%;">4100</div>
                    <div class="ScreenSize" style="display:flex; color:red; width: 100%;">1500</div>
                </div>
            </td>
        </tr>
        <tr class="Color">
            <td>Color</td>
            <td>Blue</td>
            <td>Red</td>
            <td>Black</td>
        </tr>
    </tbody>
    </table>
    </div>

Редактировать: Исправлена ​​ошибка в имени класса таблицы jQuery 'CompTable', указанном в комментарии ниже.

...