Javascript在数据表过滤或分页之后不工作

Javascript not working after Datatable Filter or Paging

本文关键字:之后 工作 分页 数据表 过滤 Javascript      更新时间:2023-09-26

我正在使用Django ListView来显示发票列表。我试图使用Javascript发送更新。例如,当支付发票时,用户可以单击该行的图标,该发票将被标记为已支付。一切都运行良好,但是,我使用datatable允许用户进行二次过滤。在页面加载时,javascript和对服务器的调用工作得很好,但是,当使用过滤器或分页时,javascript不拾取行号。为了简单起见,我用alert()函数对它进行了测试——下面是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:

$(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);
    });
});    

任何想法?提前感谢!

你应该把点击事件委托给最近的静态容器:

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

忽略click事件的原因是因为在绑定它时,只有DOM中可用的匹配元素才能获得事件绑定。Datatable插件修改table内容,删除/添加分页/过滤的新元素。通过将其绑定到table元素(最接近的静态元素),您也可以处理所有这些动态元素。

[引用]

    代表团
  • jQuery .fn.on美元()
相关文章: