来自Ajax源的DataTables按数据顺序和显示格式化日期 [英] DataTables from Ajax source order-by data-order and display formatted date

查看:77
本文介绍了来自Ajax源的DataTables按数据顺序和显示格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想将数据从ajax中提取到我的列中,但是我希望列中的单元格具有数据顺序属性,并带有来自ajax调用并使用moment.js格式化单元格中的数据。

Basically I want to pull data from ajax into my columns, but I want the cells in the columns to have the data-order attribute on them with the value from the ajax call and use moment.js to format the data in the cell.

我认为这是使其漂亮且可订购的最佳方式。我找到了datetime-momentJS的插件,但它只会订购日期,而不是格式化它。

I'm assuming this is the best way to make it pretty AND orderable. I found the plugin for datetime-momentJS, but it will only order the date, not format it as well.

var dataTable = $('#products').DataTable( {
  'processing': true,
  'ajax': '/products',
  'columns': [
    {
      'data': 'updated_at',
      'className':'date'
    }
  ]
});

现在我将此作为最终结果:

right now I have this as the final result:

<td class="date">2015-11-08T11:00:00.000Z</td>

但我想要的结果是:

<td class="date" data-order="2015-11-08T11:00:00.000Z">11/08/2015</td>

我可以使用 render 选项来做不知何故?

Can I use the render option to do this somehow?

我想要格式化它的时刻代码将是时刻('2015-11-08T11:00:00.000Z') .format('DD / MM / YY')

The moment code to format it like I want would be moment('2015-11-08T11:00:00.000Z').format('DD/MM/YY').

推荐答案

你可以用 createdRow 回调以便在行之后应用任何自定义逻辑创建:

You can use createdRow callback in order to apply any custom logics after row creation:

$('#products').dataTable({
  /* */
  'createdRow': function(row, data, dataIndex) {
      var $dateCell = $(row).find('td:eq(0)'); // get first column
      var dateOrder = $dateCell.text(); // get the ISO date
      $dateCell
          .data('order', dateOrder) // set it to data-order
          .text(moment(dateOrder).format('DD/MM/YY')); // and set the formatted text
  }
});

请注意 td:eq(0) selector假定带有日期的列是第一列。如果不是,则需要将0更改为其他值。

Note that td:eq(0) selector assumes that the column with date is the first column. You need to change 0 to another value, if it's not.

这篇关于来自Ajax源的DataTables按数据顺序和显示格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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