简体   繁体   中英

Datatables: Need to sort a column numerically by data in HTML

I have a table that looks like this...

<table id="myTable">
    <tr>
        <td><a href="site.com?id=1">1</a></td>
        <td>Foo</td>
    </tr>
    <tr>
        <td><a href="site.com?id=9">9</a></td>
        <td>Bar</td>
    </tr>
    <tr>
        <td><a href="site.com?id=10">10</a></td>
        <td>Baz</td>
    </tr>
</table>

I need to make it so my Bootstrap Datatables scripting will sort by the inner HTML of the anchor tag, and sort it numerically. Currently it is sorting it like this...

1   Foo
10  Baz
9   Bar

But I need it to be sorted like this...

1   Foo
9   Bar
10  Baz

I'm not really sure how to go about this. I have it sorting, but it thinks the inner HTML is a string, not a number :(

I'm assuming you are generating your links server-side. You are better off rendering these on the client for two reasons:

  1. Your sort will work
  2. Your payload will be smaller

To do this you need to use aoColumnsDef and aTargets similar to the below

    "aoColumnDefs": [
    {
        "aTargets": [ 1 ],
        "fnRender": function ( o, val ) {
          var link = "<a class='' href='site.com?id=" + o.aData[0] + "'>" + o.aData[0] + "</a>";
          return link;
        }
    },

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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