gpt4 book ai didi

javascript - 我想使用所选按钮的 id,但如何从中获取 id? this.id 不起作用

转载 作者:行者123 更新时间:2023-12-02 23:18:44 31 4
gpt4 key购买 nike

我想使用所选按钮的 ID 进行删除。但我不知道如何从中获取/获取 id。我尝试了 this.id 但不起作用。

这是我创建按钮的地方:

var deleteEmployer= document.createElement("td");

var deleteEmployerButton= document.createElement("input");
deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.setAttribute("value", "delete");
deleteEmployerButton.setAttribute("id", employer.employer_id);
deleteEmployer.appendChild(deleteEmployerButton);

deleteEmployer.addEventListener("click", deleteEmployFunc);
row.appendChild(deleteEmployer);

document.querySelector("#Employer").appendChild(row);

这是deleteEmployFunc:

function deleteEmployFunc() {
var id = this.id;

console.log(id);

fetch("restservices/employer/" + id, { method: 'DELETE' })
.then(function (response) {
if (response.ok) {
window.location.reload();
} else if (response.status == 404) {
console.log("Employer not found")
} else {
console.log("Can't delete employer")
}
});
}

最佳答案

您要将事件处理程序添加到 deleteEmployer 而不是 deleteEmployerButton

这是一个应该可行的最小示例:

var deleteEmployerButton = document.createElement("input");
deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.setAttribute("value", "delete");
deleteEmployerButton.setAttribute("id", "randomID");

deleteEmployerButton.addEventListener("click", deleteEmployFunc);

document.querySelector("#Employer").appendChild(deleteEmployerButton);



//This is the "deleteEmployFunc" :

function deleteEmployFunc() {

var id = this.id;

console.log(id);

fetch("restservices/employer/" + id, {method: 'DELETE'} )
.then(function (response) {
if (response.ok) {
window.location.reload();
} else if (response.status == 404) {
console.log("Employer not found")
} else {
console.log("Can't delete employer")
}
});
}
<div id="Employer"></div>

当您单击该按钮时,您应该会看到输出randomID

关于javascript - 我想使用所选按钮的 id,但如何从中获取 id? this.id 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57046603/

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