简体   繁体   English

选择一行并单击数据表中的按钮后获取表行的行 ID

[英]Get row id of a table row after selecting a row and clicking the button in datatables

What I want to achieve is to display a table and after selecting a row, make it possible to edit or delete a row (make a proper query) so I need a primary key which I don't want to display.我想要实现的是显示一个表,在选择一行后,可以编辑或删除一行(进行适当的查询),所以我需要一个我不想显示的主键。 My table looks like this:我的桌子看起来像这样:

<table id='documents_d' class='display'>
    <thead>
        <tr><th>title 1</th><th>title 2</th><th>title 3</th>
    </thead>
    <tbody>
        <tr data-id='1'>
            <td>content</td>
            <td>content</td>
            <td>content</td>
        <tr data-id='2'>
            <td>content</td>
            <td>content</td>
            <td>content</td></tr>
    </tbody>
</table>

I use the following script to get the datatables running:我使用以下脚本来运行数据表:

<script>
    $(document).ready(function () {
        var documents_d = $('#documents_d').DataTable({
            paging: true,
            dom: 'Blfrtip',
            colReorder: true,
            select: {style: 'single'},
            rowId: 'Writer',
            buttons: [
                'colvis',
                'excelHtml5',
                {
                    text: 'Edit',
                    action: function () {
                        alert(documents_d.row('.selected').data());
                    }
                }
            ]
        });
    });
</script>

Instead of an alert I want to run a function like editDocument($docID).我想运行像 editDocument($docID) 这样的函数而不是警报。 So first I want to select a row (this is working fine) and after clicking 'Edit' I want to get the 'data-id' and run a function.因此,首先我想选择一行(这工作正常),然后单击“编辑”后,我想获取“数据 ID”并运行一个函数。 I tried:我试过:

documents_d.row('.selected').data("data-id")

but this would give me an error:但这会给我一个错误:

DataTables warning: table id=documents_d - Requested unknown parameter '7' for row 1, column 7. For more information about this error, please see http://datatables.net/tn/4 DataTables 警告:table id=documents_d - 为第 1 行第 7 列请求未知参数“7”。有关此错误的更多信息,请参阅http://datatables.net/tn/4

You probably want this:你可能想要这个:

$(documents_d.row('.selected').node()).data('id');

However, there's another way:然而,还有另一种方式:

https://datatables.net/reference/option/rowId https://datatables.net/reference/option/rowId

It can often be useful to have a id attribute on each tr element in a DataTable for row selection and data source identification, particularly when using events.在 DataTable 中的每个tr元素上都有一个id属性用于行选择和数据源标识通常很有用,尤其是在使用事件时。

Then you can use:然后你可以使用:

documents_d.row('.selected').id();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM