【问题标题】:jquery dataTables - how to extract row data onclick eventjquery dataTables - 如何在点击事件中提取行数据
【发布时间】:2015-07-23 07:45:13
【问题描述】:

我正在尝试熟悉 jquery dataTables 插件:http://www.datatables.net/manual/server-side#Sent-parameters

工作原理

我有 json 数据从服务器返回到我的客户端,并且正在填充表。

什么不起作用

当最终用户选择/单击该行时,我需要能够捕获给定行中的数据。

这是我的代码:http://jsfiddle.net/e3nk137y/1515/

$("#users tr").click(function(){
  alert($(this).find("pID").val());
   });

上面的javascript是我一直在玩的。麻烦的是,ajax 调用是自动发生的,而我不是在表中创建行的人。最终,我需要能够抓取每行中的一些字段,除了 ID / pID

到目前为止我所做的尝试

除了玩 javascript 代码之外,我也一直在审查这个:http://datatables.net/examples/api/select_single_row.html 但是在那个例子中,所有的数据都是在客户端定义的,所以很容易为每个表行指定一个 id 或一个类

任何建议将不胜感激。

【问题讨论】:

    标签: jquery html ajax jquery-datatables


    【解决方案1】:

    希望这就是你要找的东西

    HTML

    <table id="users" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th id="pID">ID</th>
                <th>Name</th>
                <th>Code</th>
                <th>Available</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1-1</td>
                <td>1-2</td>
                <td>1-3</td>
                <td>1-4</td>
            </tr>
            <tr>
                <td>2-1</td>
                <td>2-2</td>
                <td>2-3</td>
                <td>2-4</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Code</th>
                <th>Available</th>
            </tr>
        </tfoot>
    </table>
    

    脚本

    $(document).ready(function () {   
        var table = $('#users').DataTable();
        $('#users tbody').on('click', 'tr', function () {
            console.log(table.row(this).data());
        });
    });
    

    Fiddle Link

    【讨论】:

    • 很高兴它帮助了你:)
    • @Matthias 检查浏览器控制台的结果/输出。它工作正常。
    【解决方案2】:

    你的小提琴中的错误:

    • 您使用 datatables 方法调用,但只添加了 bootstrap-table 库。
    • Ajax 无法正常工作,但我们现在可以忽略它。
    • 若要将事件也绑定到将由数据表插入的表行,请将其绑定到表并在 on() 方法中将 tr 用作 selector
    • 如果你想find()element by id,你需要使用#。但请注意,如果有多个元素,则不能使用 id,请改用 class
    • 表格单元格没有值,因此请使用text() 而不是val()

    更新功能:

    $("#users").on('click', 'tr', function () {
        alert($(this).find("#pID").text());
    });
    

    Updated fiddle

    【讨论】:

      【解决方案3】:
      var Table = $('#CheckinTable').DataTable( {
       // optional info
      });
      
      
      $('#CheckinTable tbody').on('click', 'tr', function () {
        let bookingData = Table.row(this).data();
        // do your staff
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-25
        • 1970-01-01
        • 1970-01-01
        • 2012-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        相关资源
        最近更新 更多