如何在数据表中的每一行添加按钮?

时间:2014-03-18 06:28:28

标签: javascript jquery datatables

我是DataTables的新手。我想在每一行添加按钮进行编辑和删除(如下图所示)

enter image description here

我尝试过代码:

Test.cfm

<table id="myDataTable" class="table table-striped table-bordered">
<thead>
    <tr>
        <th>UserID</th>
        <th>Name</th>
        <th>UserName</th>
        <th>Passowrd</th>
        <th>Email</th>
         <th>IsActive</th>
         <th>Command</th>
    </tr>
</thead>
<tbody> 
</tbody>

$(document).ready(function () {
    var oTable = $('#myDataTable').dataTable({
       // "bServerSide": true,
        "sAjaxSource": "fetchUserData.cfm",
        "bProcessing": true,
        "sPaginationType": "full_numbers",
        "aoColumns": [
            { "mData": null },
            { "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
            { "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
            { "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%"  },
            { "mData": "Email","sTitle": "Email"  , "sWidth": "20%"},
            { "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
            {
                "mData": null,
                "bSortable": false,
               "mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
            }
        ]
    });

} );

fetchUserData.cfm

{
"aaData": [
    [
        "1",
        "sameek",
        "sam",
        "sam",
        "sameek@test.com",
        "1",
        ""
    ],
    [
        "2",
        "arun singh",
        "arun",
        "arun",
        "arunsingh@test.com",
        "0",
        ""
    ],
    [
        "9",
        "s s",
        "sam3",
        "sam3",
        "ss@s.com",
        "0",
        ""
    ],
    [
        "10",
        "sameek mishra",
        "sam56",
        "sam",
        "same@s.com",
        "0",
        ""
    ],
    [
        "11",
        "narendra kumar",
        "narendra",
        "nav",
        "sa@sa.com",
        "1",
        ""
    ],
    [
        "12",
        "test test",
        "test",
        "test",
        "test2@test.com",
        "1",
        ""
    ]
]
 }

8 个答案:

答案 0 :(得分:35)

基本上你的代码没问题,这是正确的方法。无论如何,有一些误解:

  1. fetchUserData.cfm不包含键/值对。因此,解决mData中的密钥没有意义。只需使用mData[index]

  2. 即可
  3. dataTables希望您的服务器端提供更多信息。至少你应该告诉datatables你的服务器端总共有多少项目以及过滤了多少项目。 我刚刚将这些信息硬编码到您的数据中。您应该从服务器端脚本中的计数中获取正确的值。

    {
     "iTotalRecords":"6",
     "iTotalDisplayRecords":"6",
      "aaData": [
    [
        "1",
        "sameek",
        "sam",
        "sam",
        "sameek@test.com",
        "1",
        ""
    ],...
    
  4. 如果您已在html部分中设置了列名,则无需添加sTitle。

  5. mRender功能有三个参数:

    • data =此单元格的数据,如mData
    • 中所定义
    • type =数据类型(主要可以忽略)
    • full =此行的完整数据数组。
  6. 所以你的mRender功能应如下所示:

      "mRender": function(data, type, full) {
        return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
      }
    

    找到一个有效的Plunker here

答案 1 :(得分:6)

看看这里......这对我很有帮助 https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

答案 2 :(得分:3)

var table =$('#example').DataTable( {
    data: yourdata ,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "parent" },
        { data: "date" },

        {data: "id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="<?php echo $delete_url;?>'+ data +'" ><i class="fe fe-delete"></i></a>' :
                data;
            }},
    ],
    }
}

答案 3 :(得分:1)

我提供按钮设置:查看,编辑和删除。 最后一列有数据:null 最后用属性defaultContent添加一个HTML代码的字符串。并且因为它是最后一列,所以在指示列时通过targets属性用索引-1表示。

//...
columns: [
    { title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
    { title: "Id", "data": "id", defaultContent: '', "visible":false },
    { title: "Nombre", "data": "nombre" },
    { title: "Apellido", "data": "apellido" },
    { title: "Documento", "data": "tipo_documento.siglas" },
    { title: "Numero", "data": "numero_documento" },
    { title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
    { title: "Teléfono", "data": "telefono1" },
    { title: "Email", "data": "email1" }
    , { title: "", "data": null }
],
columnDefs: [
    {
        "searchable": false,
        "orderable": false,
        "targets": 0
    },
    { 
      width: '3%', 
      targets: 0  //la primer columna tendra una anchura del  20% de la tabla
    },
    {
        targets: -1, //-1 es la ultima columna y 0 la primera
        data: null,
        defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button>  <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
    },
    { orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
], 
//...

enter image description here

答案 4 :(得分:0)

我的食谱:

数据表声明:

defaultContent: "<button type='button'....

事件:

$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }

答案 5 :(得分:0)

使用响应式数据表时此解决方案不起作用

答案 6 :(得分:0)

看看。

$(document).ready(function () {     
        $('#datatable').DataTable({
            columns: [
                { 'data': 'ID' },
                { 'data': 'AuthorName' },
                { 'data': 'TotalBook' },
                { 'data': 'DateofBirth' },
                { 'data': 'OccupationEN' },   
                { 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
            ],            
            bServerSide: true,
            sAjaxSource: 'EmployeeDataHandler.ashx'           
        });       
    });

答案 7 :(得分:-1)

好吧,我刚刚在数据中添加了button。 例如, 我应该这样编码:

$(target).DataTable().row.add(message).draw()

然后,在message中,我添加了这样的按钮:[blah, blah ... "<button>Click!</button>"]并且..它起作用了!