简体   繁体   English

如何使用javascript或jquery对可编辑表进行排序

[英]How to sort the editable table using javascript or jquery

I have an editable table in which we can add, delete and edit rows. 我有一个可编辑的表,可以在其中添加,删除和编辑行。 How can I sort them by storing them dynamically without a database just for static sake 我如何通过静态存储而无需数据库就将它们动态存储以对其进行排序

You could try a plugin like https://datatables.net/ which could have this and more features. 您可以尝试使用https://datatables.net/这样的插件,该插件可能具有此功能以及更多功能。 However you could always try some code like this: 但是,您总是可以尝试这样的代码:

var tbl = $("table#yourtblID");
var rows = $("tr", tbl);
rows.sort(conditionFunction);
$("tr", tbl).remove();

In order to use the above code, you can need to create a conditionFunction. 为了使用上面的代码,您可能需要创建一个conditionFunction。 Lets say you would like to sort based on a column called id with all its td tags having the class tid 假设您要基于名为id的列进行排序,其所有td标签的类均为tid

function conditionFunction(a,b){
    return $("td", a).text()-$("td", b).text();
}

To know more about these condition functions refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort 要了解有关这些条件函数的更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

There is tablesorter jquery plugin available for sorting your table. tablesorter jquery插件可用于对表进行排序。

Demo : https://jsfiddle.net/Prakash_Thete/q8sh28dh/ . 演示: https : //jsfiddle.net/Prakash_Thete/q8sh28dh/

Here is the sample code for the same 这是相同的示例代码

HTML : HTML:

 <table id="myTable" class="tablesorter">
    <thead>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Email</th>
        <th>Due</th>
        <th>Web Site</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Smith</td>
        <td>John</td>
        <td>jsmith@gmail.com</td>
        <td>$50.00</td>
        <td>http://www.jsmith.com</td>
    </tr>
    <tr>
        <td>Bach</td>
        <td>Frank</td>
        <td>fbach@yahoo.com</td>
        <td>$50.00</td>
        <td>http://www.frank.com</td>
    </tr>
    <tr>
        <td>Doe</td>
        <td>Jason</td>
        <td>jdoe@hotmail.com</td>
        <td>$100.00</td>
        <td>http://www.jdoe.com</td>
    </tr>
    <tr>
        <td>Conway</td>
        <td>Tim</td>
        <td>tconway@earthlink.net</td>
        <td>$50.00</td>
        <td>http://www.timconway.com</td>
    </tr>
    </tbody>
</table> 

JS : JS:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.26.5/js/jquery.tablesorter.js"></script> 

$(document).ready(function() {
   $("#myTable").tablesorter(); 
});

For info on plugin please visit http://tablesorter.com/docs/ 有关插件的信息,请访问http://tablesorter.com/docs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM