我有一個客戶端的 HTML 表,我希望能夠洗掉其中一個,這要歸功于一個簡單的 axios 洗掉請求。為此,我必須獲取要洗掉的客戶端的 ID。所以這就是我所做的:
async function deleteClient(e) {
e.preventDefault();
const id = document.getElementById("client").innerHTML;
console.log(id);
axios
.delete("http://localhost:8080/api/clients/" id)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
deleteClient 函式在表中呼叫 onClick。問題是,它只會獲取第一行客戶端的 ID,而永遠不會獲取下面行中的 ID。我該怎么做才能獲得正確的 ID 并能夠洗掉其他客戶?
有關資訊,這是我的 HTML 表,它是動態填充的,這要歸功于 useEffect 鉤子和一個簡單的 axios get 請求:
<table className="text-white border-2 border-bikeexplogray-light rounded-full">
<tr>
<th>Clients</th>
</tr>
<tr>
<th>ID</th>
<th>Store Name</th>
<th>Username</th>
<th>Email</th>
<th>Phone number</th>
<th>Address</th>
<th>Zipcode</th>
<th>City</th>
<th>Website</th>
<th>Delete</th>
</tr>{" "}
{filteredData.map((value, index) => {
return (
<tr key={value.id}>
<td id="client">{value.id}</td>
<td>{value.storeName}</td>
<td>{value.username}</td>
<td>{value.email}</td>
<td>{value.phone}</td>
<td>{value.adress}</td>
<td>{value.zipcode}</td>
<td>{value.city}</td>
<td>{value.website}</td>
<td>
<button onClick={deleteClient}>Delete</button>
</td>
</tr>
在此先感謝您的幫助!
uj5u.com熱心網友回復:
您可以輕松獲取要洗掉的客戶的 ID,因為您在map()函式中。您的每一行都有一個key等于的 unical value.id,因此您可以按如下方式修改按鈕來達到目的:
<button onClick={(e) => deleteClient(e, value.id)}>Delete</button>
并且不要忘記修改您的deleteClient功能:
async function deleteClient(e, id) {
e.preventDefault();
//const id = document.getElementById("client").innerHTML;
console.log(id);
axios
.delete("http://localhost:8080/api/clients/" id)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
uj5u.com熱心網友回復:
標簽上的id屬性在td檔案中必須是唯一的。
您可以data-id改用,data-*只是將資料附加到 DOM 的標準方式。
在您的事件處理程式deleteClient中,您可以使用它e.currentTarget來訪問背景關系。
function deleteClient(e) {
// this will be your button element
const button = e.currentTarget
// search up the DOM tree (each parent) for this selector match
const td = button.closest("tr > td[data-id]")
// this should be the ID from the data-* attribute
console.log(td.dataset.id)
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426154.html
標籤:javascript 反应 dom
