簡體   English   中英

無法使用本地按鈕刪除jQuery DataTable的當前行

[英]Can't delete current row of jQuery DataTable using local button

我有一個jQuery Datatable,並動態添加行。 每行都有一個單元格,其中有一個刪除按鈕。 我的問題是我無法使用按鈕刪除行,甚至無法定位當前行。

這是我的DataTable代碼:

var tab_presta = $("#tableau_presta").DataTable({
    "searching": false,
    "paging":   false,
    "ordering": false,
    "info":     false,
    responsive: true,
    "language": {
        "emptyTable": "No product added to the contract for the moment."
      }
});

這是我如何在提交事件上的每一行上創建按鈕的方法:

form2.on('submit', function (event) {

tab_presta.row.add( 
    [            
        '<center><button type="button" id="btn_supp' + (++idCount) + '" onclick="alert(this.parentNode)" class="btn btn-xs btn-block btn-danger confirmation">Delete</button></center>'
    ] 
)
.draw( false );

// here I dynamically add an id to each button based on a variable
$('.btn btn-xs btn-block btn-danger confirmation').each(function() {
        $(this).attr('id', 'suppr' + idCount);
        idCount++;
    });
});

這是我單擊每個按鈕時要刪除的代碼:

for (j = 0; j <= btn_count; j++) {
    $("#tableau_presta").on("click", btn_supp[j], function(){
        //tab_presta.row($(this).parents('tr')).remove().draw(false);
        var row = $(this).closest("tr");
        console.log(row);
    });
}

如您所見,我評論了remove()部分,因為它不起作用,所以我試圖找到$(this) (button)的最接近tr ,但結果是控制台中沒有該行。 它是空的,我不明白為什么,因為按鈕實際上存在,並且如果我單擊onclick"alert(this.id) ,則單擊該按鈕即可獲取其ID。

任何想法 ?

您無需在循環內綁定click事件。 而是使用class屬性選擇器 在這種情況下,選擇id^所有元素都以btn_supp = [id^=btn_supp]

 $("#tableau_presta").on("click", "[id^=btn_supp]", function() { $(this).closest("tr").remove(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tableau_presta"> <tr> <td> <button type="button" id="btn_supp1" class="btn btn-xs btn-block btn-danger confirmation">Delete</button> </td> </tr> <tr> <td> <button type="button" id="btn_supp2" class="btn btn-xs btn-block btn-danger confirmation">Delete</button> </td> </tr> </table> 

暫無
暫無

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

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