簡體   English   中英

數據表過濾器或分頁后Javascript不起作用

[英]Javascript not working after Datatable Filter or Paging

我正在使用Django ListView顯示發票清單。 我正在嘗試使用Javascript發送更新。 例如,當發票已付款時,用戶可以單擊該行的圖標,該發票將被標記為已付款。 一切工作正常,但是,我正在使用數據表來允許用戶進行二次過濾。 在頁面加載時,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);
    });
});    

有任何想法嗎? 提前致謝!

您應該將click事件委托給最接近的靜態容器:

$('#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元素(最接近的靜態元素),您也可以處理所有這些動態元素。

[參考]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM