jQuery DataTables获取选定的行值

Ara*_*mar 22 jquery datatables

我正在使用jQuery datatable.I使用http://www.datatables.net/examples/api/select_row.html完成它 现在我想得到选定的行值id

脚本:

 $(document).ready(function() {
 var table = $('#example').DataTable();
 $('#example tbody').on( 'click', 'tr', function () {
    $(this).toggleClass('selected');
} );

$('#button').click( function () {
    alert( table.rows('.selected').data().length +' row(s) selected' );
} );
} );
Run Code Online (Sandbox Code Playgroud)

和HTML代码:

 <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Id</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>

    <tbody>
        <tr>
            <td>1</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
         </table>
Run Code Online (Sandbox Code Playgroud)

现在我可以选择no.of.rows.Now我想要选择行ID.任何人都可以指导我实现它.

Aru*_*hny 38

您可以迭代行数据

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


leo*_*ole 6

更多评论而不是答案 - 但我还不能添加评论:感谢您的帮助,计数很容易.只为可能来到这里的其他人.我希望它会为你节省一些时间.

我花了一段时间从行中获取属性并了解如何从data()对象访问它们(data()是一个数组,并且可以通过添加点而不是括号来读取属性:

$('#button').click( function () {
    for (var i = 0; i < table.rows('.selected').data().length; i++) { 
       console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
    }
} );
Run Code Online (Sandbox Code Playgroud)

(顺便说一句:我使用AJAX和JSON获取我的表的数据)


小智 6

var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);
Run Code Online (Sandbox Code Playgroud)