DataTables - 在每一行的单元格中显示一个按钮

2022-01-01 00:00:00 datatables jquery php laravel-5.1

我使用的是 jQuery DataTables 插件,并且在初始化中我使用的是 "drawCallback" 更改行的外观.

I'm using the jQuery DataTables plugin and within the initialization I'm using the "drawCallback" to make changes to the look of the rows.

我的代码如下:

        "drawCallback": function() {
            table.rows().every( function() {
                var d = this.data();
                var option = this.find('.options');

                if (d.activated) {
                    option.html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');
                } else {
                    option.html('<button class="btn btn-mini btn-danger pull-right"> Disabled</button>');
                }
            });

         }

然而 this.find('.options') 部分没有做任何事情.

However the this.find('.options') part isn't doing anything.

基本上我想:

  1. 获取当前行
  2. 选择我为选项"指定了类名的列
  3. 在此处插入与行数据相关的按钮

HTML:

<table id="example">
<thead>
<tr>
   <th></th>
   <th>Last Name</th>
   <th>First Name</th>
   <th>Email</th>
   <th></th>
</tr>
</thead>
</table>

数据表初始化:

var table = $('#example').DataTable( {
   columns: [
        {
            "className":      'center',
            "data":           null,
            "defaultContent": ''
        },
        {
            data: 'last_name'
        },
        {
            data: 'first_name'
        },
        {
            data: 'email'
        },
        {
            "className":      'options',
            "data":           null,
            "defaultContent": ''
        }
    ],

    // ...and so on

最初我有以下有效的代码:

Originally I had the following code which worked:

$('td.options').html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');

但这是不加选择的行数据,只是为每一行粘贴了相同的按钮.

but this was indiscriminate of the row data and simply pasted the same button for each row.

推荐答案

使用列.render 选项来定义为单元格生成内容的函数.

Use columns.render option to define a function producing content for the cell.

var table = $('#example').DataTable( {
   columns: [
        {
            "className":      'center',
            "data":           null,
            "defaultContent": ''
        },
        {   "data": 'last_name' },
        {   "data": 'first_name' },
        {   "data": 'email'  },
        {
            "className":      'options',
            "data":           null,
            "render": function(data, type, full, meta){
               if (full.activated) {
                   return '<button class="btn btn-mini btn-primary pull-right"> Enabled</button>';
               } else {
                   return '<button class="btn btn-mini btn-danger pull-right"> Disabled</button>';
               }
            }
        }
    ],

    // ...and so on

});

相关文章