简体   繁体   English

数据表过滤器或分页后Javascript不起作用

[英]Javascript not working after Datatable Filter or Paging

I am using Django ListView to display a list of invoices. 我正在使用Django ListView显示发票清单。 I am trying to use Javascript to send updates. 我正在尝试使用Javascript发送更新。 For example, when the invoice is paid, the user can click on the icon of the row and that invoice will be marked as paid. 例如,当发票已付款时,用户可以单击该行的图标,该发票将被标记为已付款。 Everything is working well, but, I am using datatable to allow the user a secondary filtering. 一切工作正常,但是,我正在使用数据表来允许用户进行二次过滤。 On page load, the javascript and call to server works fine, however, when filter or paging is used, Javascript is not picking up the row number. 在页面加载时,javascript和对服务器的调用可以正常工作,但是,当使用过滤器或页面调度时,Javascript无法获取行号。 Just for simplicity, I test it with a alert() function - here's the html 为了简单起见,我使用alert()函数对其进行了测试-这是html

HTML: HTML:

<table width="100%" class="table table-striped table-bordered table-hover" id="dt-invoice">
    <thead>
        <tr>
            <th></th>
            <th>Inoice Number</th>
            <th>Description</th>
            <th>Date Sent</th>
        </tr>
    </thead>
    <tbody>
    {% csrf_token %}
    {% for i in invoice %}
        <tr id="{{ i.invoice }}">
            <td><a id='id_paid-{{ i.id }}' title="I Got This!" href="#"><i class="fa fa-check fa-fw"></i></a></td>
            <td>i.invoice_number</td>
            <td>i.invoice_description</td>
            <td>i.invoice_sent_date</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Javascript: Javascript:

$(document).ready(function() {    
    $('#dt-invoice').DataTable({
        buttons: [ 'copy', 'csv', 'excel', 'pdf','print'],
        "iDisplayLength": 10,            
        "processing": true,
        responsive: true,
        "dom": '<"top pull-left" li><"top pull-right" f> <t> <"bottom pull-left" iB><"bottom pull-right" p>',
    });

    $('[id^=id_paid-]').click(function(){
        console.log("HERE")
        row = $(this).closest('tr');
        trid = row.attr("id");
       alert(trid);
    });
});    

Any ideas? 有任何想法吗? Thanks in advance! 提前致谢!

You should delegate click event to closest static container: 您应该将click事件委托给最接近的静态容器:

$('#dt-invoice').on('click', '[id^=id_paid-]', function() {
  console.log("HERE")
  row = $(this).closest('tr');
  trid = row.attr("id");
  alert(trid);
});

The reason your click event was ignored is because at time you are binding it, only available matching elements in DOM get the event bound. click事件被忽略的原因是因为在绑定该事件时,只有DOM中可用的匹配元素才绑定该事件。 Datatable plugin modify the table content, removing/adding new elements on paging/filtering. Datatable插件可修改table内容,在分页/过滤时删除/添加新元素。 By binding it to table element (the closest static one), you handle all these dynamic elements too. 通过将其绑定到table元素(最接近的静态元素),您也可以处理所有这些动态元素。

[References] [参考]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM