table按自定义列排序
<!DOCTYPE html> <html> <head> <title>如何使用js使table按照表头排序</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> </head> <body> <div style="text-align: center;margin: 10px;"> <input type="text" id="xu" value="cdeab" /> <button type="button" style="width:100px;">按照表头排序</button> </div> <table class="table table-hover" style="width: 80%;text-align:center;margin: 0 auto;border: 0;" id="sorttable"> <thead class="thead-dark"> <tr> <th>a</th> <th>b</th> <th>c</th> <th>d</th> <th>e</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>4</td> <td>3</td> <td>2</td> <td>1</td> </tr> <tr> <td>5</td> <td>4</td> <td>3</td> <td>2</td> <td>1</td> </tr> <tr> <td>5</td> <td>4</td> <td>3</td> <td>2</td> <td>1</td> </tr> <tr> <td>5</td> <td>4</td> <td>3</td> <td>2</td> <td>1</td> </tr> <tr> <td>5</td> <td>4</td> <td>3</td> <td>2</td> <td>1</td> </tr> </tbody> </table> </body> <script type="text/javascript"> jQuery.fn.swapWith = function (to) { return this.each(function () { var copy_to = $(to).clone(true); var copy_from = $(this).clone(true); $(to).replaceWith(copy_from); $(this).replaceWith(copy_to); }); }; jQuery.moveColumn = function (table, from, to) { var rows = jQuery(‘tr‘, table); var cols; rows.each(function () { cols = jQuery(this).children(‘th, td‘); cols.eq(from).swapWith(cols.eq(to)); }); }; function getIndex(colName) { var nIndex = 99; $(‘#sorttable tr th‘).each(function (i) { if ($.trim($(this).html()) == colName) { nIndex = i; } }) return nIndex; } $(function () { $("button").click(function () { var tbl = $("#sorttable"); var len = $(‘#sorttable tr th‘).length; var col = $("#xu").val(); var arr = col.split(‘‘); for (var i = 0; i < arr.length; i++) { jQuery.moveColumn(tbl, getIndex(arr[i]), i); } }); }); </script> </html>
原文:https://www.cnblogs.com/webapi/p/12659662.html