You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery获取DataTable选中行的内容?

获取jQuery DataTable选中单行的内容

你现在的代码已经能统计选中行数了,要获取单行的具体内容其实很简单,DataTables的API里有专门的方法来做这个。咱们直接修改按钮的action函数就行,因为你只关注单行选中的情况,用row()(单数形式)代替rows()就能精准获取选中的那一行数据。

修改后的完整代码

HTML部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables.net/2.1.1/jquery.dataTables.min.js"></script>
<div id="events"> Row selected count - new information added at the top </div>
<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>63</td>
      <td>2011/07/25</td>
      <td>$170,750</td>
    </tr>
    <tr>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>66</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
  </tbody>
</table>

JavaScript部分

$(document).ready(function() {
  var events = $('#events');
  var table = $('#example').DataTable({
    dom: 'Bfrtip',
    select: true,
    buttons: [{
      text: 'Get selected data',
      action: function() {
        // 获取选中的单行数据
        var selectedRow = table.row({ selected: true }).data();
        
        if (selectedRow) {
          // 把行数据拼接成可读的内容展示
          var rowContent = `Selected row details: 
Name: ${selectedRow[0]}, 
Position: ${selectedRow[1]}, 
Office: ${selectedRow[2]}, 
Age: ${selectedRow[3]}, 
Start date: ${selectedRow[4]}, 
Salary: ${selectedRow[5]}`;
          events.prepend('<div>' + rowContent + '</div>');
        } else {
          events.prepend('<div>No row selected!</div>');
        }
      }
    }]
  });
});

关键代码说明

  • table.row({ selected: true }).data():这是核心,row()(单数)会返回当前选中的那一行的API实例,data()方法则会取出该行的原始数据(是一个数组,对应表格的每一列)。
  • 我们加了一个判断if (selectedRow),防止用户没选任何行就点击按钮的情况,提升体验。
  • 你可以根据自己的需求来处理selectedRow里的数据,比如只提取某一列(比如selectedRow[0]就是姓名),或者如果你的DataTables配置了columns.data,也能把数据转成对象形式访问。

如果以后需要支持多行选中,只需要把row()改成rows(),然后用each()遍历每一行的数据:

// 多行选中的处理示例
table.rows({ selected: true }).every(function() {
  var rowData = this.data();
  // 处理每一行的数据
});

内容的提问来源于stack exchange,提问作者Jeff Baker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:32:28