指定列数据类型,并使用< th>属性为DataTables [英] Specify column data type with a <th> attribute for DataTables

查看:159
本文介绍了指定列数据类型,并使用< th>属性为DataTables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We're using the DataTables jQuery plugin (http://www.datatables.net) to create sortable tables. This plugin auto-detects the data type of the data in each column.

当您想要自己指定列的数据类型时,可以添加aoColumns属性当您初始化datatable时:

When you want to specify the data type of a column yourself, you add the "aoColumns" attribute when you initialize the datatable:

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

请注意,我下载了数据类型的货币数据类型插件。这很棒。

Note, I downloaded the currency data type plugin for datatables. This works great.

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

However, I'm concerned that if we ever make changes to the table column, we'll forget to go back into the JS and change how the datatables plugin is initialized on that table.

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

So... It would be ideal to specify the data types directly in the table as necessary:

<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属性?

Is there any way to do this, either with default functionality of DataTables (which I can't find) or using a JS loop or something to loop through the tags of the table and update the sType where "sType" attribute exists?

推荐答案

感谢大家的帮助!我不得不对Russell Zahniser的评论进行一些调整,以便为我工作:

Thanks to all for your help! I had to make a couple tweaks to Russell Zahniser's comment for it to work for me:


  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
});

这篇关于指定列数据类型,并使用&lt; th&gt;属性为DataTables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆