将点击事件添加到数据表

SA_*_*A__ 5 html javascript php jquery datatables

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

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

这是构造的表格.

我想写点击功能.我该怎么做 ?

<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>
Run Code Online (Sandbox Code Playgroud)

我想将click事件写入role ="row"并获取其值TMB030.

我怎样才能做到这一点 ?

我试过这样的

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

但它没有触发我怎么能这样做?请帮忙

Naq*_*lik 8

它应该是这样的:

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

简要说明:首先,在DOM中不存在应用click事件的元素,即div[role='row'].其次,你必须动态绑定click事件,因为你绑定click事件的时间DataTable没有完全加载,并且你还没有应用click事件的元素.


San*_*yak 5

将您的点击更改为:

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

样本:

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


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


cra*_*aro 5

如果要通过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())
            });
        }
});
Run Code Online (Sandbox Code Playgroud)