将单击事件添加到数据表

Adding click events to Datatables

本文关键字:数据表 添加 事件 单击      更新时间:2023-09-26

这是我的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')
    });
});

但它没有被触发,我怎么能做到呢?请帮助

应该是这样的:

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

简要说明:

  1. 在初始页面加载时(即执行document.ready回调函数时),数据表元素(行和列等)尚未出现在DOM树中。它们是在运行时创建的,以响应数据更改。因此,document.click方法中提供的回调函数将不会绑定到任何元素(即div[role='row']
  2. 为了克服这一问题,.on方法是可行的。它将回调函数绑定到DOM中已有元素的点击事件,也绑定到动态创建的元素

如果您通过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())
            });
        }
});

将您的点击更改为:

 $( "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>

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

所以将代码更改为低于

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

试试看:

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