繁体   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