gpt4 book ai didi

javascript - 从数据库中填充的动态创建的表中删除一行,并从数据库中删除该项目

转载 作者:行者123 更新时间:2023-11-30 06:16:45 24 4
gpt4 key购买 nike

我无法在 delete 方法的 ajax 调用中将要删除的项目(行)引用为 url。

    let retrieve = () => {
$.ajax({
url: "/api/contributors",
method: "GET",
contentType: "application/x-www-form-urlencoded",
headers: {
"Content-Type": "application/json"
}
}).then(function(response) {
let result = response;
console.log(result);
info.push(result);
console.log(info);
console.log(info[0]);
// console.log(info[0][0]._id)
let records = info[0].map(r => {
return r;
})
console.log(records);

$("#data").append( "<table class='table table-dark'>" +
'<thead class="thead thead-dark">' +
'<tr>'+
'<th scope="col">' + 'ID' + '</th>' +
'<th scope="col">' + 'Title' + '</th>' +
'<th scope="col">' + 'Name' + '</th>' +
'<th scope="col">' + 'Address' + '</th>' +
'<th scope="col">' + 'Phone Number' + '</th>' +
'<th scope="col">' + 'Email' + '</th>' +
'<th scope="col">' + 'Date' + '</th>' +
// '<th scope="col">' + 'Rate' + '</th>' +
'</tr>' +
'</thead>' )

records.forEach(record => {
$(".table").append("<tbody>" +
"<tr>" +
"<td>" + record._id + "</td>" +
"<td>" + record.title + "</td>" +
"<td>" + record.name + "</td>" +
"<td>" + record.address + "</td>" +
"<td>" + record.phoneNumber + "</td>" +
"<td>" + record.email + "</td>" +
"<td>" + record.creation_date + "</td>" +
"<td>" +
"<button id='' class='btn btn-warning btn-sm update'>" +
"Update" +
"</button>" +
"</td>" +
"<td>" +
"<button id='' class='btn btn-danger btn-sm delete'>" +
"Delete" +
"</button>" +
"</td>" +
"</tr>" +
"</tbody>" +
"</table>"
);
})

});
}

下面是我遇到困难的地方。上面的一切都按预期工作。

      let del = (event) => {
event.stopPropagation();
let listItemData =
$(this).parent("td").parent("tr").parent("tbody").data("customer");

console.log(listItemData);
let id = listItemData;
// let id = $(this).data("id");
console.log(id);
$.ajax({
url: "/api/contributors/" + id,
method: "DELETE"
}).then(retrieve)
}

$(document).on("click", "button.delete", del);

我希望表中的项目被删除,但是 listItemData 显示为未定义。因此 url 显示为“/api/contributors/undefined”导致错误。

最佳答案

尝试使用 event.currentTarget:

$(event.currentTarget).parent("tbody").data("customer");

您可以消除其他 parent 调用,因为 parent 向上遍历 DOM 以找到选择字符串的第一次出现。

关于javascript - 从数据库中填充的动态创建的表中删除一行,并从数据库中删除该项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55681201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com