【问题标题】:Specify column data type with a <th> attribute for DataTables使用 DataTables 的 <th> 属性指定列数据类型
【发布时间】:2013-03-22 16:00:30
【问题描述】:

我们正在使用 DataTables jQuery 插件 (http://www.datatables.net) 创建可排序表。该插件自动检测每列数据的数据类型。

当你想自己指定一个列的数据类型时,你在初始化数据表时添加“aoColumns”属性:

$('#accountTable').dataTable({
    "bPaginate": false,
    "sScrollX": "100%",
    "bScrollCollapse": true,
    "aoColumns": [
        null,
        null,
        { "sType": "currency" },
        { "sType": "currency" }
    ]
});

注意,我下载了数据表的货币数据类型插件。这很好用。

但是,我担心如果我们对表列进行更改,我们会忘记返回 JS 并更改数据表插件在该表上的初始化方式。

所以...根据需要直接在表中指定数据类型是理想的:

<table class="dataTables display">
    <thead>
        <tr>
        <th>Category</th>
        <th>Product</th>
        <th sType="currency">Cost</th>
        <th sType="currency">Retail</th>
        ...

有什么办法可以做到这一点,要么使用 DataTables 的默认功能(我找不到),要么使用 JS 循环或其他东西来循环表的标签并更新存在“sType”属性的 sType ?

【问题讨论】:

  • 使用 HTML 自定义数据属性——在构建配置数据结构时只需选择它们的内容。

标签: javascript jquery datatables


【解决方案1】:

这是一个绝对的方法:

您的标题 HTML:

<table id="sorted-table">
    <thead>
        <tr>
            <th data-s-type="string">Number</th>
            <th data-s-type="html">Complex Name</th>
            <th>Price</th>
            <th data-b-sortable="false">Action</th>
         </tr>
     </thead>
...

你的 JS:

$('#sorted-table').dataTable({
   ...
   "aoColumns": $('#sorted-table').find('thead tr th').map(function(){return $(this).data()})
});

注意:数据属性中的那些破折号是必需的。它们通过 jQuery 转换为 camelCase 形式,使其与数据表 API 兼容。

【讨论】:

  • 是的,这真是一个很棒的解决方案!不错!
【解决方案2】:

接受 CBroe 的评论,这正是我所做的。只需确保您的自定义属性以data- 为前缀,例如data-stype='currency'HTML specs

【讨论】:

    【解决方案3】:

    让你的 JS 循环并检查标题上的属性会起作用,但你不能只是发明一个 sType 属性并让它显示在 DOM 中。您必须破坏一个有效但未使用的属性,例如 headers(这可能会给屏幕阅读器带来麻烦;可能有更好的选择)。

    编辑:

    好的,阅读了 CBroe 的评论,我想give an element an arbitrary attribute.

    可能的

    所以,如果您想符合 HTML5,您可以将属性命名为 data-sType,然后执行以下操作:

    var aoColumns = [];
    
    $('#accountTable > th').each(function() {
       var sType = $(this).getAttribute("data-sType");
       aoColumns.push(sType ? sType : null);
    });
    
    $('#accountTable').dataTable({
       ...
       "aoColumns": aoColumns
    });
    

    【讨论】:

    • 太棒了!这几乎是完美的。必须做一些小调整才能让它为我工作。看我的评论。
    【解决方案4】:

    感谢大家的帮助!我必须对 Russell Zahniser 的评论进行一些调整才能为我工作:

    1. 将 $('#accountTable > th') 更改为 $('#accountTable thead th')
    2. 将 aoColumns.push(sType ? sType : null) 更改为 aoColumns.push(sType ? { "sType" : "currency" } : null)

    最终结果:

    var aoColumns = [];
    
    $('#accountTable thead th').each(function() {
       var sType = $(this).getAttribute("data-sType");
       aoColumns.push(sType ? { "sType" : "currency" } : null);
    });
    
    $('#accountTable').dataTable({
       ...
       "aoColumns": aoColumns
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多