我正在用从 firebase 数据库获取的一些数据填充一个表,为此我使用了append()
$("#table_body").append("<tr><td>" + nome + "</td>" +
"<td>" + marca + "</td>" +
"<td>" + modelo + "</td>" +
"<td>" + setor + "</td>" +
"<td>" + responsavel + "</td>" +
"<td><div buttons>"+
"<button>Delete</button>"+" "+
"<button>Edit</button>"+
"</div></td></tr>");
但是,我不知道如何使用表格每一行上的“删除”和“编辑”按钮,我不应该有每一行的 ID 吗?那么,如果动态添加行,如何获取每行的 ID?
最佳答案
您有一个来自数据模型的对象 ID ...将其作为属性添加到行中。
然后使用遍历到closest()
用于隔离实例的行
以下假设添加了一个按钮:
<tr data-id="idFromFirebaseObject">
....
<button class="delete-btn">Delete</button>
然后使用事件委托(delegate)来考虑运行时尚不存在的元素
$("#table_body").on('click','.delete-btn', function(e){
// "this" is element event occurred on
var $row = $(this).closest('tr'),
rowId = $row.data('id');
// do your thing with FB then in success callback remove row
....
$row.remove();
})
关于javascript - 从 "append(<tr><td="ID 获取 ID">...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838887/