Javascript fetch delete 如何删除html

Javascript fetch delete how to delete html

问题:当我的标题 1(或 2 或 3,...)从服务器上的 JSON 中删除时,我想删除 HTML 行。但是我只能在刷新时才能执行此操作。

我尝试在每次 fetch 调用后添加 AddCards 方法,但随后我需要删除所有 tr 元素,但我也试过了。

这是网站的图片。

Picture of the site

这是 javascript 代码:

let form = document.getElementById('frm');
form.addEventListener('submit', PostBlog)
let alleposts = {};
let numOfPosts = 0;
getPosts();

function PostBlog(event) {
    event.preventDefault()
    let title = document.getElementById("txtTitle");
    let content = document.getElementById("txtContent");
    let data1 = {content: content.value,title:title.value};
    fetch("/posts",
    {
        method: 'POST',
        mode:'same-origin',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data1),
    }
).then(receive).then(response => (response).text()).then(Succeed).catch(problem);
}
function receive(response) {
    if(!(response.ok)){
        throw new Error("Didn't Receive " + response.status);
    }
    return response;
}
function problem(error){
    alert("Not Found " + error);
}
function Succeed(data){
    alert("Found " + data);
    getPosts();
}

function getPosts(){
    fetch("/posts",{
        method:'get',
        headers: {
            'Accept': 'application/json',
        }
    }).then(receive).then(response => response.json()).then(Succeed2).catch(problem);
}

function Succeed2(data){
    alert("Found " + JSON.stringify(data));
    data.forEach((data) => alleposts[`${data.title}`] = data.uuid);
    AddCards();

}

function AddCards(){

    Object.keys(alleposts).forEach((sleutel)=>{VoegVorigePostToe(sleutel)});
}

function Succeed3(data){
    alert("Found " + data);
    numOfPosts--;
}

function DeletePost(event){
    let title = event.target.parentNode.previousElementSibling.innerText;
    console.log(title);
    let key = alleposts[title];
    console.log("alle keys " + JSON.stringify(key));
    fetch(`/posts/${key}`,{
        method:'delete',
        headers: {
            'Accept': 'application/json',
        }
    }).then(receive).then(response => (response).text()).then(Succeed3).catch(problem);
}




function VoegVorigePostToe(title){
    //let title = document.getElementById("txtTitle");
    let thead = document.getElementsByTagName("thead")[0];

    let th = document.createElement("tr");
    let td = document.createElement("td");
    td.setAttribute("id", "th_" + numOfPosts);
    td.innerText = title;
    let delete_button = document.createElement("td");
    let button = document.createElement("button");
    button.innerHTML = "Delete";
    button.addEventListener("click",DeletePost)



    delete_button.appendChild(button);
    th.appendChild(td);
    th.appendChild(delete_button);
    thead.appendChild(th);
    numOfPosts++;

}

htmlid's like frm=form,txtTitle=title输入框

已经解决了:

function DeleteRow(event) {
    let btn = event.target;
    $(btn).closest("tr").remove();
}