javascript - Bootstrap Datatables 按部分单元格内容排序

标签 javascript jquery twitter-bootstrap sorting datatables

我在对数据表进行排序时遇到问题。我有一个列显示服务器中的玩家,如“0/50”,当我尝试对该列进行排序时,它没有正确排序数字。它将按如下顺序显示:

  • 0/50
  • 10/30
  • 2/40
  • 3/30
  • 4/30
  • 9/25

我只想按第一个数字排序。例如:

  • 0/50
  • 2/40
  • 3/30
  • 4/30
  • 9/25
  • 10/30

我知道这可以通过将 2 个值分开到它们自己的列中来完成,但出于美观原因,我希望它们位于同一列中。

这是我的 HTML 布局:

<div class="row">
    <div class="col-lg-12">
        <table id="serverList" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Server Infomation</th>
                    <th>Players</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

这是我的 Javascript:

$(document).ready(function() {              
            var t = $('#serverList').DataTable();

            $.getJSON('../php/queryAll.php', function(data){
                var server = [];
                $.each( data, function( key, val ) {
                    $.each( val, function( key2, val2 ) {
                        server.push(val2);
                    });
                    String.prototype.replaceAll = function(str1, str2, ignore){return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);}
                    if(server[14] > 0)
                    {
                        hostName = server[1].replaceAll('[','<span style="color:#');
                        server[1] = hostName.replaceAll(']',';">');

                        t.row.add( [server[0],server[1],server[8] + ' / ' + server[7]]).draw( false );
                    }
                    server = [];
                });
                $("#loader").fadeOut(250, function(){
                    $(".row").fadeIn(1000);
                });
            });
        });

感谢您提供的任何帮助。

最佳答案

就像其他人提到的那样,问题是由于斜杠,数据表正在使用字符串排序。

我解决这个问题的方法是附加一个带有数值的隐藏跨度。您只需要记住使所有值的长度相同,因为它们仍将按字符串排序。您可以通过附加 0 来做到这一点。

一个例子[假设我知道我的数字永远不会超过 100]:

<td><span style="display:none">024</span>24/60</td>
...
<td><span style="display:none">001</span>1/60</td>
...
<td><span style="display:none">051</span>51/60</td>
...
<td><span style="display:none">033</span>33/60</td>

升序排序,即使是字符串,也会得到 1、24、33、51

如果你也可以在数字后添加单词,你可以使用这个技巧:

<td><span style="display:none">050</span>50 Hours</td>

关于javascript - Bootstrap Datatables 按部分单元格内容排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33874552/

相关文章:

twitter-bootstrap - GRAILS 3.1.0 不显示 Bootstrap 字形

jquery - 使用 Bootstrap 的响应图像

twitter-bootstrap - 如何在 yii2 alpha 中将 bootstrap3 图标添加到事件表单中

javascript - 是否可以使用 JavaScript 编写后端?

javascript - 显示 JavaScript 函数/值

javascript - jquery : access element inside an angular *ngIf directive

javascript - 这是有效的 jquery 拆分吗?

javascript - Angular 2.如何将组件替换或包含到文本中

javascript - 简单的 React Redux 入门包 |发电机

javascript - 删除jquery中ul的第一个li