[英]How can I delete from a JSON file and from the HTML?
我有這個代碼,但現在我不知道如何從那里刪除,如果我點擊 X。我想找到行的 id,然后把它放在 url 之后。 現在我不知道如何找到ID。
const tBody = document.getElementById("tbody");
var url = "http://localhost:3000/users";
//
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {document.addEventListener('DOMContentLoaded', (event) => {
tBody.innerHTML="";
for(let i = 0; i < data.length; i++){
let newRow = document.createElement("tr");
newRow.innerHTML = `
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].author}</td>
<td> <button class="delete btn btn-primary">X</button> </td>`
tBody.appendChild(newRow);
}
});
});
//
const submitButton = document.getElementById("submit-button");
const titleInput = document.getElementById("inputTitle");
const authorInput = document.getElementById("inputAuthor");
submitButton.addEventListener("click", function(e){
e.preventDefault();
var newUser = {
title: titleInput.value,
author: authorInput.value,
};
var van = true;
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
if (data[i].title===titleInput.value || data[i].author===authorInput.value) {
var z = i + 1;
var x = "/" + z;
var postUrl = url + x;
fetch(postUrl, {
method: 'PUT',
body: JSON.stringify(
{
title: titleInput.value,
author: authorInput.value,
id: data[i].id
}
),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
van = false;
}
}
if(van===true) {
fetch(url, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(newUser)
}).then(response => response.json)
.then(json => console.log(json));
}
});
});
我試過這個:
var tomb = [];
const removeTomb=(id)=>{
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
var b = {
id: data[i].id,
title: data[i].title,
author: data[i].author
}
tomb.push(b);
console.log(tomb);
}
let index=tomb.findIndex(tomb => tomb.id==id);
tomb.splice(index,1);
console.log(tomb);
});
};
我把這個onclick="removeTomb(${tomb[i].id})"
放在 X 之前,但它不起作用,因為 removeTomb 是未定義的。 你能解釋一下它是如何工作的嗎? 我想從中學習! 非常感謝!
使用const
, function 文字方式不適用於 HTML onclick="removeTomb(${tomb[i].id})"
。 嘗試function removeTomb
或將 function 分配給 window。
window.removeTomb = removeTomb
或者
var tomb = [];
function removeTomb(id) {
fetch(url, { method: "get" })
.then((result) => {
return result.json();
})
.then((data) => {
for (let i = 0; i < data.length; i++) {
var b = {
id: data[i].id,
title: data[i].title,
author: data[i].author,
};
tomb.push(b);
console.log(tomb);
}
let index = tomb.findIndex((tomb) => tomb.id == id);
tomb.splice(index, 1);
console.log(tomb);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.