我想向状态为ORDERED的每一行添加删除按钮。我尝试了不同的变化。即使data [i]没有未定义,该解决方案也可以正常工作,不会出现错误“无法读取未定义的属性'id'”。 .click()给出正确的ID之前发出警报。怎么了我可以在这里做些不同的事情还是做得更好?
).done( (data, status, jqXHR) => {
if(data[0].order_username != undefined) {
$("#orders_table").empty();
for(var i = 0; i < data.length; i++) {
var button = "";
if(data[i].status == "ORDERED") {
button = "<td><button class='delete'>Delete</button></td>";
}
$("#orders_table").append(
"<tr>" +
"<td>" + data[i].order_username + "</td>"+
"<td>" + data[i].work_description + "</td>" +
"<td>" + dateFormatter(data[i].orderdate) + "</td>" +
"<td>" + dateFormatter(data[i].startdate) + "</td>" +
"<td>" + dateFormatter(data[i].readydate) + "</td>" +
"<td>" + dateFormatter(data[i].accepteddate) + "</td>" +
"<td>" + dateFormatter(data[i].denieddate) + "</td>" +
"<td>" + data[i].comment_of_work + "</td>" +
"<td>" + data[i].hours + "</td>" +
"<td>" + data[i].approx_budget + "</td>" +
"<td>" + data[i].status + "</td>" +
button +
"</tr>"
)
alert(data[i].id);
$(".delete").click(() => {
deleteUser(data[i].id);
})
}
}
function deleteUser(key) {
$.ajax(
{
url: "http:localhost:3001/workorders_delete/"+key,
method: 'delete'
}).done( (data, status, jqXHR) => {
}).fail( (jqXHR, status, errorThrown) => {
console.log("Call failed: "+errorThrown);
});
}
最佳答案
您可以使用响应数据中的ID为删除按钮设置唯一的数据属性,如下所示:
if(data[i].status == "ORDERED") {
button = "<td><button class='delete' data-deleteId =
"+data[i].id+">Delete</button></td>";
}
然后您可以为删除按钮编写一个单击事件侦听器,如下所示:
$(".delete").click(function(){
var id = $(this).data("deleteId");
deleteUser(id);
});
在您的代码中:-
$(".delete").click(() => {
deleteUser(data[i].id);
});
单击时将调用或执行函数deleteUser(),此时不会定义data [i] .id。