在jQuery DataTable中获取选定行/行的列值

3

我被以下代码卡住了。我想要获取数据表中所选行/行的列值。我已经使用了以下代码:

数据表的代码:

var table = $('#tableId').DataTable({
        "ajax": {
            "url": "Content",
            "dataSrc": "",
            data: {sectionUrl: "", siteUrl: siteurl}
        },
        "columns": [
//            {"defaultContent": "<input type='checkbox' name='vehicle' id='checkID'>"},
            {"data": "postIMAGE", "render": function (data) {
                    return '<img src=' + data + ' width="154" height="115"/>';
                }},
            {"data": "postTITLE"},
            {"data": "postURL", "render": function (data) {
                    return '<a href=' + data + ' target="_blank"/>' + data + '</a>';
                }},
            {"data": "postSection"}

        ]
    });

.

$('#tableId tbody').on('click', 'tr', function () {
    $(this).toggleClass('selected');
});

$('#button').click(function () {

    var selectedRows = table.rows('.selected').data();
    var results = "";

    for (i = 0; i < selectedRows.length; i++) {
        alert();
    }
});

我想获取列的值


你尝试过 alert(selectedRows[i]) 吗? - Sunil
是的,它返回一个对象。不知道如何读取该对象。我尝试使用 (selectedRows[i].length),但在提示框中显示未定义。 - Amal Madawa
你能发布你收到的对象吗? - Sunil
警告显示 [object Object]。 - Amal Madawa
请查看已发布的答案。 - Sunil
2个回答

2
你可以通过以下方式访问对象的值:

object.key

$('#button').click(function () {

   var selectedRows = table.rows('.selected').data();

 //if you are getting array of objects inside main object
   alert(selectedRows[0].postTITLE);
   alert(selectedRows[0].postURL);

  // if you are getting just plain object you can access it as
    alert(selectedRows.postTITLE);
    alert(selectedRows.postURL);
});

0
你可以通过Datatable的列名在服务器端渲染中访问选定的行。
$('#button').click(function (){
   let rows = $('#tableElement').rows( { selected: true } ).data().map(x=>x.cols_name).toArray();
         console.log(rows);
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接