[英]Can't delete current row of jQuery DataTable using local button
I have a jQuery Datatable and I dynamically add rows. 我有一个jQuery Datatable,并动态添加行。 Each row has a cell in which there's a delete button.
每行都有一个单元格,其中有一个删除按钮。 My problem is that I can't get to delete the rows with the buttons and I can't even manage to target the current row.
我的问题是我无法使用按钮删除行,甚至无法定位当前行。
Here's my DataTable code : 这是我的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."
}
});
Here is how I create the buttons on each row (on a submit event) : 这是我如何在提交事件上的每一行上创建按钮的方法:
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++;
});
});
And here is my code for deleting when clicking on each button : 这是我单击每个按钮时要删除的代码:
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);
});
}
As you can see I commented the remove() part because it doesn't work, so I tried to find the closest tr
of $(this) (button)
, but I don't get the row in the console as a result. 如您所见,我评论了remove()部分,因为它不起作用,所以我试图找到
$(this) (button)
的最接近tr
,但结果是控制台中没有该行。 It's empty and I don't understand why because the button actually exists and I can get its id when I click on it if I put a onclick"alert(this.id)
. 它是空的,我不明白为什么,因为按钮实际上存在,并且如果我单击
onclick"alert(this.id)
,则单击该按钮即可获取其ID。
Any idea ? 任何想法 ?
You don't need to bind the click event inside of a loop. 您无需在循环内绑定click事件。 Instead, use a
class
or an attribute selector . 而是使用
class
或属性选择器 。 In this case, selecting all elements with an id
that ^
starts with btn_supp
= [id^=btn_supp]
. 在这种情况下,选择
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.