【问题标题】:How do I add button on each row in datatable?如何在数据表的每一行上添加按钮?
【发布时间】:2014-04-23 16:35:04
【问题描述】:

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

我已经尝试过代码:

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",
        ""
    ]
]
 }

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

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

    1. fetchUserData.cfm 不包含键/值对。所以在 mData 中寻址键是没有意义的。只需使用mData[index]

    2. dataTables 需要您的服务器端提供更多信息。至少你应该告诉数据表你的服务器端总共有多少项目以及有多少被过滤。 我只是将此信息硬编码到您的数据中。您应该从服务器端脚本中的计数中获取正确的值。

      {
       "iTotalRecords":"6",
       "iTotalDisplayRecords":"6",
        "aaData": [
      [
          "1",
          "sameek",
          "sam",
          "sam",
          "sameek@test.com",
          "1",
          ""
      ],...
      
    3. 如果你已经在html部分设置了列名,则不需要添加sTitle。

    4. mRender 函数接受三个参数:

      • data = 此单元格的数据,在 mData 中定义
      • type = 数据类型(大部分可以忽略)
      • full = 此行的完整数据数组。

    所以你的 mRender 函数应该是这样的:

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

    找到一个可以工作的 Plunker here

    【讨论】:

    • 如果您想将多个按钮添加到单个列中,您会怎么做?
    • 我确实回答了这个问题。您要做的是返回每个按钮的数组。 return new array('&lt;a class="btn btn-info btn-sm" href=#/' + full[0] + '&gt;' + 'Edit' + '&lt;/a&gt;', '&lt;a class="btn btn-info btn-sm" href=#/' + full[0] + '&gt;' + 'Delete' + '&lt;/a&gt;');。当然,使用 new array() 是不受欢迎的(使用 []),但这个想法是成立的。
    • 是否可以在预数据表转换的&lt;html&gt; 中添加按钮?我的页面有 6 列,但最右边的 2 列是静态按钮。当我将它们中的每一个放在每行中,然后使用服务器端获取具有 4 个键值对的 JSON 对象数组时,HTML 会在开始时显示 2 个按钮,但随后会立即隐藏它们。
    • 抱歉迟到的评论...但是如何将Click 事件添加到anchortag 中?
    【解决方案2】:
    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;
                }},
        ],
        }
    }
    

    【讨论】:

    • 在回答问题时,您应该提供解释以及解决方案,而不仅仅是发布代码。这将使答案对原始发布者以及可能发现此问题的其他人更有用。
    • 太好了,我认为这种方法比其他方法更有意义。然而,我在附加 JS 函数时遇到了一些麻烦。
    【解决方案3】:

    看看这里...这对我很有帮助 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 ] );
        } );
    } );
    

    【讨论】:

      【解决方案4】:

      我贡献了我的按钮设置:查看、编辑和删除。 最后一列有数据: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

      【讨论】:

        【解决方案5】:

        看一看。

        $(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'           
                });       
            });
        

        【讨论】:

          【解决方案6】:

          我的食谱:

          数据表声明:

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

          事件:

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

          【讨论】:

            【解决方案7】:

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

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

            而且,在message 中,我添加了这样的按钮:[blah, blah ... "&lt;button&gt;Click!&lt;/button&gt;"] 并且.. 它有效!

            【讨论】:

              猜你喜欢
              • 2021-01-16
              • 2018-07-01
              • 1970-01-01
              • 1970-01-01
              • 2016-09-13
              • 2018-07-11
              • 1970-01-01
              • 2012-05-04
              • 2021-02-08
              相关资源
              最近更新 更多