Javascript 对特定列数据应用条件 - jquery DataTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33192879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:45:38  来源:igfitidea点击:

Apply a condition on specific column data - jquery DataTable

javascriptjqueryhtmldatatables

提问by Lion King

Firstly, I have the following table:

首先,我有下表:

The column which enclosed by red color display 2 types of account, the value 1= Freeand value 2= paid(free, paid accounts).

红色围起来的一栏显示了两种类型的账户,价值1=Free和价值2= paid(免费,付费账户)。

I want before rendering the data, apply a condition to change the 1to freeand 2to paid.

我想在渲染数据之前,应用一个条件来更改1tofree2to paid

that's it.

就是这样。

Table initialization:

表初始化:

var dataTableY = $('#table').DataTable({
    serverSide: true,
    ajax: {
        url: 'directory/class/method'
    },
    processing: true,
    scrollY: 400,
    paging: true,
    info: true,
    select: {
        style: 'os'
    },
    pagingType: 'full_numbers',
    language: {
        url: 'DataTables/lang/english.json'
    }
});

回答by davidkonrad

Use a column renderer:

使用列渲染器

var table = $('#example').dataTable({
    //...
    columnDefs : [
        { targets : [4],
          render : function (data, type, row) {
             return data == '1' ? 'free' : 'paid'
          }
        }
   ]
})   

The render function will return 'free'if the column value is 1, otherwise 'paid'. You could use a switchif you have more values, or for example need to return a 'N/A'too.

'free'如果列值为 1,渲染函数将返回,否则返回'paid'switch如果您有更多值,或者例如也需要返回 a,则可以使用 a 'N/A'



    columnDefs : [
        { targets : [4],
          render : function (data, type, row) {
            switch(data) {
               case '1' : return 'free'; break;
               case '2' : return 'paid'; break;
               default  : return 'N/A';
            }
          }
        }
   ]