向Datatables添加点击事件

7

这是我的Jquery数据表格,用于从ajax获取值并放置它们。

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": "data/arrays.txt"
    });
});

这是构建好的表格。

我想写一个点击函数给它。我应该怎么做?

<table id="example" class="table dataTable no-footer" role="grid" aria-describedby="example_info" style="width: 299px;">
    <tbody>
        <tr role="row" class="odd">
            <td class="sorting_1">TMB030</td>
            <td>Sample Collected</td>
        </tr>
        <tr role="row" class="even">
            <td class="sorting_1">TMB033</td>
            <td>Sample Collected</td>
        </tr>
    </tbody>
</table>

我想要为 role="row" 写一个点击事件,并获取其中的值 TMB030

我该怎么做?

我尝试了以下方法:

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": "myOrders/" + Cookies.get('userSession')
    });
    $("div[role='row']").click(function() {
        alert('clicked')
    });
});

但是它没有触发,我该怎么办?请帮忙。

难道不应该是tr[role='row']吗? - Sandeep Nayak
5个回答

10

应该像这样:

$( document ).on("click", "tr[role='row']", function(){
    alert($(this).children('td:first-child').text())
});

简要说明:

  1. 在初始页面加载时(也就是执行 document.ready 回调函数时),Datatable 元素(行和列等)尚未存在于 DOM 树中。它们是在运行时响应数据变化而创建的。因此,在 document.click 方法中提供的回调函数将不会绑定到任何元素(即 div[role='row'])。
  2. 为了克服这个问题,可以使用 .on 方法。它将回调函数绑定到已经存在于 DOM 中的元素的点击事件上,并且还可以绑定到动态创建的元素上。

请在您的回答中添加更多描述 - dreamweiver
description has been added. - Naqash Malik

8
如果您正在通过ajax加载表格,最好使用dataTable的“initComplete”函数,这样当您完全确定所有行都存在时,就可以将事件绑定到表格中的任何元素。
$('#example').DataTable({
    "ajax": "myOrders/" + Cookies.get('userSession'),
    "initComplete": function () {
            $( document ).on("click", "tr[role='row']", function(){
                 alert($(this).children('td:first-child').text())
            });
        }
});

5

将您的点击更改为以下内容:

 $( "tr[role='row']" ).on("click",function(){
     alert($(this).find("td:first-child").text());
});

示例:

$(document).ready(function() {


  $("tr[role='row']").on("click",function() {
    alert($(this).find("td:first-child").text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="table dataTable no-footer" role="grid" aria-describedby="example_info" style="width: 299px;">
  <tbody>
    <tr role="row" class="odd">
      <td class="sorting_1">TMB030</td>
      <td>Sample Collected</td>
    </tr>
    <tr role="row" class="even">
      <td class="sorting_1">TMB033</td>
      <td>Sample Collected</td>
    </tr>
  </tbody>
</table>


1

.click事件不会绑定到动态元素上,在您的情况下,行将在ajax调用后加载。

因此,请将代码更改为以下内容

$("tr[role='row']" ).on('click', function(){
  alert('clicked')
});

0

试一下:

$( document ).on("click", "#example tr[role='row']", function(){
       alert($(this).children('td:first-child').text())
});

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