ฉันมีตาราง HTML ง่าย ๆ ที่มี 4 คอลัมน์:
Facility Name, Phone #, City, Specialtyฉันต้องการให้ผู้ใช้สามารถจัดเรียงตามชื่อสิ่งอำนวยความสะดวกและเมืองเท่านั้น
ฉันจะรหัสนี้โดยใช้ jQuery ได้อย่างไร
ฉันมีตาราง HTML ง่าย ๆ ที่มี 4 คอลัมน์:
Facility Name, Phone #, City, Specialtyฉันต้องการให้ผู้ใช้สามารถจัดเรียงตามชื่อสิ่งอำนวยความสะดวกและเมืองเท่านั้น
ฉันจะรหัสนี้โดยใช้ jQuery ได้อย่างไร
คำตอบ:
หากคุณต้องการหลีกเลี่ยง bells และ whistles ทั้งหมดแล้วฉันขอแนะนำปลั๊กอินง่าย ๆ นี้sortElementsได้ไหม การใช้งาน:
var table = $('table');
$('.sortable th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){
        var th = $(this),
            thIndex = th.index(),
            inverse = false;
        th.click(function(){
            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                if( $.text([a]) == $.text([b]) )
                    return 0;
                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;
        });
    });และตัวอย่าง (คลิกส่วนหัวคอลัมน์ "เมือง" และ "สิ่งอำนวยความสะดวก" เพื่อจัดเรียง)
Error: illegal characterhtml ไม่เหมือนกันฉันยังมี thead and tboy คุณช่วยฉันด้วยได้มั้ย
                    $.text([a]) == $.text([b])ใช้$.text([a]).toUpperCase() == $.text([b]).toUpperCase()จะแก้ไขได้
                    ฉันเจอสิ่งนี้และคิดว่าฉันโยนเงิน 2 เซ็นต์ไปแล้ว คลิกที่ส่วนหัวของคอลัมน์เพื่อเรียงจากน้อยไปมากและอีกครั้งเพื่อเรียงจากมากไปน้อย
$('th').click(function(){
    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])}
})
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() }table, th, td {
    border: 1px solid black;
}
th {
    cursor: pointer;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>
    <tr><td>USA</td><td></td><td>-6</td></tr>
</table>tds เช่นนับถือการเรียงลำดับ<a href="#">Test</a> <a...การจัดเรียงข้อความเดียวที่คุณต้องมีการเปลี่ยนแปลงในบรรทัดสุดท้ายที่จะhtml() text()
                    comparer(..)หากคุณรู้ว่าคุณต้องการสนับสนุนรูปแบบใด) ในขณะเดียวกันถ้าคุณใช้yyyy-MM-dd" string" จะสั่งการเรียงลำดับข้อมูลสำหรับคุณ เช่นjsbin.com/pugedip/1
                    โดยที่ง่ายที่สุดที่ฉันเคยใช้คือ: http://datatables.net/
น่าอัศจรรย์ที่ง่าย ... เพียงแค่ให้แน่ใจว่าถ้าคุณไปเส้นทาง DOM ทดแทน (IE, การสร้างตารางและให้ DataTables ฟอร์แมตมัน) แล้วให้แน่ใจว่าการจัดรูปแบบตารางของคุณด้วย<thead>และ<tbody>หรือมันจะไม่ทำงาน นั่นเป็นเพียง gotcha เท่านั้น
นอกจากนี้ยังมีการรองรับ AJAX และอื่น ๆ เช่นเดียวกับโค้ดที่ดีจริงๆมันก็ง่ายมากที่จะปิดมัน คุณจะแปลกใจในสิ่งที่คุณอาจใช้ ฉันเริ่มต้นด้วย DataTable ที่ "เปล่า" ซึ่งเรียงลำดับเพียงฟิลด์เดียวจากนั้นก็รู้ว่าคุณสมบัติบางอย่างนั้นเกี่ยวข้องกับสิ่งที่ฉันกำลังทำอยู่จริงๆ ลูกค้ารักคุณสมบัติใหม่
คะแนนโบนัสเป็น DataTables สำหรับการรองรับ ThemeRoller อย่างเต็มรูปแบบ ....
ฉันยังโชคดีกับ tableorter แต่มันก็ไม่ง่ายเลยเอกสารไม่ค่อยดีเท่าไหร่และมีคุณสมบัติที่ใช้ได้เท่านั้น
เราเพิ่งเริ่มใช้เครื่องมือเนียนนี้: https://plugins.jquery.com/tablesorter/
มีวิดีโอเกี่ยวกับการใช้งานได้ที่: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx
    $('#tableRoster').tablesorter({
        headers: {
            0: { sorter: false },
            4: { sorter: false }
        }
    });ด้วยตารางที่เรียบง่าย
<table id="tableRoster">
        <thead> 
                  <tr>
                    <th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
                    <th>User</th>
                    <th>Verified</th>
                    <th>Recently Accessed</th>
                    <th> </th>
                  </tr>
        </thead>คำตอบของฉันคือ "ระวัง" ส่วนเสริมการเรียงลำดับตาราง jQuery จำนวนมากเรียงลำดับเฉพาะสิ่งที่คุณส่งผ่านไปยังเบราว์เซอร์ ในหลายกรณีคุณต้องจำไว้ว่าตารางเป็นชุดข้อมูลแบบไดนามิกและอาจมีการรวมของบรรทัดข้อมูล
คุณพูดถึงว่าคุณมีเพียง 4 คอลัมน์ แต่ที่สำคัญกว่านั้นคือคุณไม่ต้องพูดถึงจำนวนแถวที่เราพูดถึงที่นี่
หากคุณส่งผ่าน 5,000 บรรทัดไปยังเบราว์เซอร์จากฐานข้อมูลโดยรู้ว่าตารางฐานข้อมูลจริงมี 100,000 แถวคำถามของฉันคือ: อะไรคือจุดสำคัญในการจัดเรียงตาราง ในการเรียงลำดับที่เหมาะสมคุณจะต้องส่งแบบสอบถามกลับไปที่ฐานข้อมูลและให้ฐานข้อมูล (เครื่องมือที่ออกแบบมาเพื่อเรียงลำดับข้อมูล) ทำการเรียงลำดับให้คุณ
ในการตอบคำถามของคุณโดยตรงส่วนเสริมการเรียงลำดับที่ดีที่สุดที่ฉันเคยพบคือ Ingrid มีหลายเหตุผลที่ฉันไม่ชอบโปรแกรมเสริมนี้ ("ระฆังและเสียงนกหวีดที่ไม่จำเป็น ... " ตามที่คุณเรียกว่า) แต่หนึ่งในคุณสมบัติที่ดีที่สุดในแง่ของการเรียงลำดับก็คือมันใช้ ajax และไม่ได้ ' ไม่คิดว่าคุณได้ส่งผ่านข้อมูลทั้งหมดก่อนที่จะเรียงลำดับ
ฉันรู้ว่าคำตอบนี้น่าจะเกินกำลัง (และเกิน 2 ปี) สำหรับความต้องการของคุณ แต่ฉันรู้สึกรำคาญเมื่อผู้พัฒนาในสาขาของฉันมองข้ามจุดนี้ ดังนั้นฉันหวังว่าจะมีคนอื่นหยิบมันขึ้นมา
ฉันรู้สึกดีขึ้นแล้วตอนนี้.
นี่เป็นวิธีที่ดีในการจัดเรียงตาราง:
$(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
ฉันชอบคำตอบที่ได้รับการยอมรับอย่างไรก็ตามคุณไม่ค่อยได้รับข้อกำหนดในการจัดเรียง html และไม่ต้องเพิ่มไอคอนที่ระบุทิศทางการเรียงลำดับ ฉันรับตัวอย่างการใช้งานของคำตอบที่ยอมรับและแก้ไขได้อย่างรวดเร็วโดยเพียงแค่เพิ่ม bootstrap ในโครงการของฉันและเพิ่มรหัสต่อไปนี้:
<div></div>
ภายในแต่ละข้าง<th>เพื่อให้คุณมีสถานที่ตั้งไอคอน
setIcon(this, inverse);
จากการใช้งานของคำตอบที่ยอมรับด้านล่างบรรทัด:
th.click(function () {
และโดยการเพิ่มวิธี setIcon:
function setIcon(element, inverse) {
        var iconSpan = $(element).find('div');
        if (inverse == false) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-up');
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-down');
        }
        $(element).siblings().find('div').removeClass();
    }นี่คือการสาธิต - คุณต้องเรียกใช้การสาธิตใน Firefox หรือ IE หรือปิดใช้งานการตรวจสอบประเภท MIME ของ Chrome เพื่อให้การสาธิตทำงานได้ ขึ้นอยู่กับปลั๊กอิน sortElements เชื่อมโยงโดยคำตอบที่ยอมรับเป็นทรัพยากรภายนอก แค่หัวขึ้น!
นี่คือแผนภูมิที่อาจเป็นประโยชน์ในการตัดสินใจว่าจะใช้อย่างไร: http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-l ไลบรารี/
@Nick Grealy คำตอบนั้นยอดเยี่ยม แต่ก็ไม่ได้คำนึงถึงrowspanคุณลักษณะที่เป็นไปได้ของเซลล์ส่วนหัวของตาราง (และอาจเป็นคำตอบอื่น ๆ ที่ไม่ได้ทำ) นี่คือการปรับปรุงคำตอบของ @Nick Grealy ซึ่งแก้ไขได้ ตามคำตอบนี้ด้วย (ขอบคุณ @Andrew Orlov)
ฉันได้เปลี่ยน$.isNumericฟังก์ชั่นเป็นแบบกำหนดเอง (ขอบคุณ @zad) เพื่อให้ใช้งานได้กับ jQuery เวอร์ชันเก่ากว่า
หากต้องการเปิดใช้งานให้เพิ่มclass="sortable"ใน<table>แท็ก
$(document).ready(function() {
    $('table.sortable th').click(function(){
        var table = $(this).parents('table').eq(0);
        var column_index = get_column_index(this);
        var rows = table.find('tbody tr').toArray().sort(comparer(column_index));
        this.asc = !this.asc;
        if (!this.asc){rows = rows.reverse()};
        for (var i = 0; i < rows.length; i++){table.append(rows[i])};
    })
});
function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index);
        return isNumber(valA) && isNumber(valB) ? valA - valB : valA.localeCompare(valB);
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() };
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
function get_column_index(element) {
    var clickedEl = $(element);
    var myCol = clickedEl.closest("th").index();
    var myRow = clickedEl.closest("tr").index();
    var rowspans = $("th[rowspan]");
    rowspans.each(function () {
        var rs = $(this);
        var rsIndex = rs.closest("tr").index();
        var rsQuantity = parseInt(rs.attr("rowspan"));
        if (myRow > rsIndex && myRow <= rsIndex + rsQuantity - 1) {
            myCol++;
        }
    });
    // alert('Row: ' + myRow + ', Column: ' + myCol);
    return myCol;
};คุณสามารถใช้ปลั๊กอิน jQuery ( สายพันธุ์ ) ที่ให้การเรียงลำดับตัวกรองและการแบ่งหน้า:
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')
    });
  });
});อันนี้ไม่วางสายเบราว์เซอร์ / s, ง่ายต่อการกำหนดค่าเพิ่มเติม:
var table = $('table');
$('th.sortable').click(function(){
    var table = $(this).parents('table').eq(0);
    var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
    this.asc = !this.asc;
    if (!this.asc)
       ths = ths.reverse();
    for (var i = 0; i < ths.length; i++)
       table.append(ths[i]);
});
function compare(idx) {
    return function(a, b) {
       var A = tableCell(a, idx), B = tableCell(b, idx)
       return $.isNumeric(A) && $.isNumeric(B) ? 
          A - B : A.toString().localeCompare(B)
    }
}
function tableCell(tr, index){ 
    return $(tr).children('td').eq(index).text() 
}ในการตอบสนองของเจมส์ฉันจะเปลี่ยนฟังก์ชั่นการเรียงลำดับเพื่อให้เป็นสากลมากขึ้น วิธีนี้มันจะจัดเรียงข้อความตามตัวอักษรและตัวเลขเช่นตัวเลข
if( $.text([a]) == $.text([b]) )
    return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
    return $.text([a]) > $.text([b]) ? 
       inverse ? -1 : 1
       : inverse ? 1 : -1;
}
else{
    return parseInt($.text([a])) > parseInt($.text([b])) ? 
      inverse ? -1 : 1
      : inverse ? 1 : -1;
}อีกวิธีในการจัดเรียงตาราง HTML (ตามW3.JS เรียง HTML )
/* Facility Name */
$('#bioTable th:eq(0)').addClass("control-label pointer");
/* Phone # */
$('#bioTable th:eq(1)').addClass("not-allowed");
/* City */
$('#bioTable th:eq(2)').addClass("control-label pointer");
/* Specialty */
$('#bioTable th:eq(3)').addClass("not-allowed");
var collection = [{
  "FacilityName": "MinION",
  "Phone": "999-8888",
  "City": "France",
  "Specialty": "Genetic Prediction"
}, {
  "FacilityName": "GridION X5",
  "Phone": "999-8812",
  "City": "Singapore",
  "Specialty": "DNA Assembly"
}, {
  "FacilityName": "PromethION",
  "Phone": "929-8888",
  "City": "San Francisco",
  "Specialty": "DNA Testing"
}, {
  "FacilityName": "iSeq 100 System",
  "Phone": "999-8008",
  "City": "Christchurch",
  "Specialty": "gDNA-mRNA sequencing"
}]
$tbody = $("#bioTable").append('<tbody></tbody>');
for (var i = 0; i < collection.length; i++) {
  $tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>');
}.control-label:after {
  content: "*";
  color: red;
}
.pointer {
  cursor: pointer;
}
.not-allowed {
  cursor: not-allowed;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>
<table id="bioTable" class="w3-table-all">
  <thead>
    <tr>
      <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th>
      <th>Phone #</th>
      <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th>
      <th>Specialty</th>
    </tr>
  </thead>
</table>ฉันลงเอยด้วยการใช้คำตอบของ Nick (ที่นิยม แต่ไม่ยอมรับ) https://stackoverflow.com/a/19947532/5271220
และรวมเข้ากับhttps://stackoverflow.com/a/16819442/5271220แต่ไม่ต้องการเพิ่มไอคอนหรือ fontawesome ในโครงการ สไตล์ CSS สำหรับ sort-column-asc / desc ฉันมีสี, padding, border border
ฉันยังแก้ไขมันให้เป็นคลาสแทนที่จะเป็นแบบอื่นดังนั้นเราจึงสามารถควบคุมได้ว่าอันไหนเรียงได้ สิ่งนี้อาจมีประโยชน์ในภายหลังหากมีสองตารางแม้ว่าจะต้องทำการแก้ไขเพิ่มเติมสำหรับสิ่งนั้น
ร่างกาย:
 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 = " ↑ " // arrow up
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-desc');
            $(iconSpan)[0].innerHTML = " ↓ " // arrow down 
        }
        $(element).siblings().find('span').each(function (i, obj) {
            $(obj).removeClass();
            obj.innerHTML = "";
        });
    }คะแนนของฉัน! jquery.sortElements.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 
One cod ดีกว่า!
ฟังก์ชั่นสำหรับทุกโต๊ะในทุก Th ตลอดเวลา ... ดูสิ! 
การสาธิต
.live()นอกเหนือจากการไม่สามารถที่จะเข้าใจคำที่ฉันจะขอแนะนำต่อ