我有一个非常简单的HTML表,有4列:

Facility Name, Phone #, City, Specialty

我希望用户只能按设施名称和城市进行排序。

我如何使用jQuery编码这个?


当前回答

你可以使用jQuery插件(breedjs)提供排序,过滤和分页:

HTML:

<table>
  <thead>
    <tr>
      <th sort='name'>Name</th>
      <th>Phone</th>
      <th sort='city'>City</th>
      <th>Speciality</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people">
      <td b-sort="name">{{person.name}}</td>
      <td>{{person.phone}}</td>
      <td b-sort="city">{{person.city}}</td>
      <td>{{person.speciality}}</td>
    </tr>
  </tbody>
</table>

JS:

$(function(){
  var data = {
    people: [
      {name: 'c', phone: 123, city: 'b', speciality: 'a'},
      {name: 'b', phone: 345, city: 'a', speciality: 'c'},
      {name: 'a', phone: 234, city: 'c', speciality: 'b'},
    ]
  };
  breed.run({
    scope: 'people',
    input: data
  });
  $("th[sort]").click(function(){
    breed.sort({
      scope: 'people',
      selector: $(this).attr('sort')
    });
  });
});

演奏小提琴的例子

其他回答

我的投票!jquery. sortelelements .js和简单的jquery 非常简单,非常简单,谢谢nandhp…

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

Dei uma melhorada do código 一条鳕鱼更好! 函数为所有表在所有Th在所有时间…看它! 演示

我最终使用了尼克的答案(最受欢迎但不被接受)https://stackoverflow.com/a/19947532/5271220

并将其与https://stackoverflow.com/a/16819442/5271220结合起来,但不想在项目中添加图标或fontawesome。对于sort-column-asc/desc的CSS样式,我设置了颜色、填充、圆角边框。

我还修改了它,按类而不是按任何,这样我们就可以控制哪些是可排序的。如果以后有两个表,这也可以派上用场,尽管需要为此做更多的修改。

身体:

 html += "<thead>\n";
    html += "<th></th>\n";
    html += "<th class=\"sort-header\">Name <span></span></i></th>\n";
    html += "<th class=\"sort-header\">Status <span></span></th>\n";
    html += "<th class=\"sort-header\">Comments <span></span></th>\n";
    html += "<th class=\"sort-header\">Location <span></span></th>\n";
    html += "<th nowrap class=\"sort-header\">Est. return <span></span></th>\n";
    html += "</thead>\n";
    html += "<tbody>\n"; ...

... 再往下看

$("body").on("click", ".sort-header", function (e) {
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc) { rows = rows.reverse() }
    for (var i = 0; i < rows.length; i++) { table.append(rows[i]) }

    setIcon(e.target, this.asc);
});

功能:

function comparer(index) {
        return function (a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text()
    }

    function setIcon(element, inverse) {

        var iconSpan = $(element).find('span');

        if (inverse == true) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-asc');
            $(iconSpan)[0].innerHTML = " &#8593 " // arrow up
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-desc');
            $(iconSpan)[0].innerHTML = " &#8595 " // arrow down 
        }

        $(element).siblings().find('span').each(function (i, obj) {
            $(obj).removeClass();
            obj.innerHTML = "";
        });
    }

这是一个排序表的好方法:

$(document).ready(function () { $('th').each(function (col) { $(this).hover( function () { $(this).addClass('focus'); }, function () { $(this).removeClass('focus'); } ); $(this).click(function () { if ($(this).is('.asc')) { $(this).removeClass('asc'); $(this).addClass('desc selected'); sortOrder = -1; } else { $(this).addClass('asc selected'); $(this).removeClass('desc'); sortOrder = 1; } $(this).siblings().removeClass('asc selected'); $(this).siblings().removeClass('desc selected'); var arrData = $('table').find('tbody >tr:has(td)').get(); arrData.sort(function (a, b) { var val1 = $(a).children('td').eq(col).text().toUpperCase(); var val2 = $(b).children('td').eq(col).text().toUpperCase(); if ($.isNumeric(val1) && $.isNumeric(val2)) return sortOrder == 1 ? val1 - val2 : val2 - val1; else return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0; }); $.each(arrData, function (index, row) { $('tbody').append(row); }); }); }); }); table, th, td { border: 1px solid black; } th { cursor: pointer; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr><th>id</th><th>name</th><th>age</th></tr> <tr><td>1</td><td>Julian</td><td>31</td></tr> <tr><td>2</td><td>Bert</td><td>12</td></tr> <tr><td>3</td><td>Xavier</td><td>25</td></tr> <tr><td>4</td><td>Mindy</td><td>32</td></tr> <tr><td>5</td><td>David</td><td>40</td></tr> </table>

提琴可以在这里找到: https://jsfiddle.net/e3s84Luw/

解释如下: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code

这里有一个图表,可能有助于决定使用哪个:http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/

我的回答是“小心”。很多jQuery表排序插件只对传递给浏览器的内容进行排序。在许多情况下,您必须记住表是动态的数据集,并且可能包含无数行数据。

你提到了你只有4列,但更重要的是,你没有提到我们在这里讨论的行数。

如果从数据库传递5000行到浏览器,知道实际的数据库表包含100,000行,我的问题是:使表可排序有什么意义?为了进行适当的排序,您必须将查询发送回数据库,并让数据库(实际上是为对数据进行排序而设计的工具)为您进行排序。

直接回答你的问题,我遇到过的最好的排序插件是Ingrid。我不喜欢这个附加组件的原因有很多(你称之为“不必要的铃铛和哨子……”),但它在排序方面最好的特性之一是它使用ajax,并且不假设在它进行排序之前已经将所有数据传递给它。

我意识到这个答案对于您的需求来说可能有些过分(并且晚了2年),但是当我所在领域的开发人员忽视这一点时,我确实很恼火。所以我希望有人能注意到。

我现在感觉好多了。