【问题标题】:JQuery Datatable get row data by clickingJQuery Datatable通过点击获取行数据
【发布时间】:2020-07-27 07:45:43
【问题描述】:

我有一个关于 jquery 数据表的小问题。我正在尝试制作表格,当我单击一行时,我需要从该行获取数据。我发现这很像例子,但对我没有用:

var table = $('#table1').DataTable();
 
$('#myTable').on( 'click', 'tr', function () {
    var id = table.row( this ).id();
 
    alert( 'Clicked row id '+id );
} );

当我尝试这样做时,id 始终未定义。

var table = $('#table1').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row(this).data();
        alert('You clicked on ' + data[0] + '\'s row');
    });
});

当我尝试这个时也是如此。我也看到了这个problem 对我没有帮助。

这是我的 HTML 表格:

<div class="container">
    <table class="table table-hover" id="table1">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Cgnome</th>
                <th>Ani</th>
                <th>Data</th>
                <th>Paese</th>
                    ....
            </tr>
        </thead>
    </table>
</div>

这就是我在 javascript 中尝试过的:

    var oTable1;
    var id;
    $('#table1').on('click', 'tbody tr', function () {
        id = this.id; // is always `id = ""`
    });

$(document).ready(function () {
    LoadMissioniOptimizer();
});

function LoadMissioniOptimizer() {
    $.ajax({
        type: "GET",
        url: "/My/GetAppSettingFromKey?key=MissioniOptimizer",
        ASYNC: true,
        dataType: "json",
        success: function (data, textStatus, xhr) {
            var apiUrl = data;
            oTable1 =
                $('#table1').DataTable({
                    ajax: '/api/staff',
                    rowId: 'staffId',
                    scrollY: '50vh',
                    scrollCollapse: true,
                    paging: false,
                    scrollX: true,
                    destroy: true,
                    serverSide: false,
                    processing: true,
                    searching: true,
                    ordering: true,
                    orderMulti: false,
                    colReorder: true,
                    paging: true,
                    columns: [
                        { "data": "Nome", responsivePriority: 1, "searchable": true },
                        { "data": "Cognome", responsivePriority: 2, "searchable": true },
                        { "data": "Ani", responsivePriority: 3, "searchable": true },
                        { "data": "Data", responsivePriority: 4, "searchable": true },
                        { "data": "Paese", responsivePriority: 5, "searchable": true },
                                     .......
                        ],
                    columnDefs: [
                        {
                            render: $.fn.dataTable.render.text(),
                            targets: 0
                        },
                        {
                            render: $.fn.dataTable.render.text(),
                            targets: 1
                        },
                        {
                            render: $.fn.dataTable.render.text(),
                            targets: 2
                        },
                        {
                            render: $.fn.dataTable.render.text(),
                            targets: 3
                        },
                        {
                            render: $.fn.dataTable.render.text(),
                            targets: 4
                        },
                    ]
                });
            $.ajaxSetup({ cache: false });
        }
    });
};

【问题讨论】:

  • 您的 HTML 中没有tbody,但您在点击功能中使用了'tbody tr'
  • Ti consiglio non solo di ripassare i selettori ma anche di Considerare qualcosa di un po' più moderno, le table fatte con jquery sono da anni 90. Se poi lo fai per studio mi scuso。
  • 即使没有 tbout 我总是得到 id = undefined
  • Cosa posso usare di piu moderno?
  • Ci sono diversi framework abbastanza conosciuti (per esempio il trio React-Vue-Angular),che hanno 来“伴奏”多样化的 librerie piuttosto fiche。 Ma mi rendo conto che per iniziare a studiare non sono il massimo。在 alternativa ci sarebbe Boostrap o Foundation... Ma di nuovo resumeto: se stai studiando le basi non è saggio sviare。 Ho detto di ripassare i selettori perché nello sn-p leggo "#example tbody",ma nell'HTML che hai aggiunto non mi sembra di vedere alcun id example。

标签: javascript jquery datatables


【解决方案1】:

我不了解数据表,但这里有一个简单的 JS,可以将所有 tr 行数据放入数组中。

只需将innerHTML 更改为您真正需要的即可。

var data = [];
[...document.querySelectorAll('tr')].forEach(tr => {
  tr.addEventListener('click', event => {
    data = [];
    [...tr.children].forEach(td => {
      data.push(td.innerHTML);
    })
    console.clear();
    console.log(data)
  })
})
<div class="container">
  <table class="table table-hover" id="table1">
    <thead>
      <tr>
        <th>Nome</th>
        <th>Cgnome</th>
        <th>Ani</th>
        <th>Data</th>
        <th>Paese</th>
      </tr>
      <tr>
        <th>Nome2</th>
        <th>Cgnome2</th>
        <th>Ani2</th>
        <th>Data2</th>
        <th>Paese2</th>
      </tr>    
    </thead>
    <tbody>
          <tr>
        <th>data1 row1</th>
        <th>data2 row1</th>
        <th>data3 row1</th>
        <th>data4 row1</th>
        <th>data5 row1</th>
      </tr>
      <tr>
        <th>data1 row2</th>
        <th>data2 row2</th>
        <th>data3 row2</th>
        <th>data4 row2</th>
        <th>data5 row2</th>
      </tr>  
      </tbody>
  </table>
</div>

【讨论】:

    【解决方案2】:

    你可以通过添加行回调函数来解决这个问题:

    简单有效的方法:

    数据表定义上添加这个函数:

            rowCallback: function(row, data, index) {
                $(row).unbind('click');
                $(row).bind('click', () => {
                  yourClickFunction(data);
                });
            }
    

    像这样:

                        .
                        .
                        .
    
    
             columnDefs: [
                    {
                        render: $.fn.dataTable.render.text(),
                        targets: 0
                    },
                    {
                        render: $.fn.dataTable.render.text(),
                        targets: 1
                    },
                    {
                        render: $.fn.dataTable.render.text(),
                        targets: 2
                    },
                    {
                        render: $.fn.dataTable.render.text(),
                        targets: 3
                    },
                    {
                        render: $.fn.dataTable.render.text(),
                        targets: 4
                    },
                ],
                rowCallback: function(row, data, index) {
                $(row).unbind('click');
                $(row).bind('click', () => {
                  yourClickFunction(data);
                });
            }
                        .
                        .
                        .
    

    你的Js文件中的这个函数,它将向你显示什么数据。

            function yourClickFunction(rowData) {
              console.log("YourClickData:", rowData);
            }
    

    DataTable官网帮助here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多