首页 > 解决方案 > 未捕获的类型错误:deleteButton 不是 HTMLButtonElement.onclick 处的函数

问题描述

我需要在我的卡片上添加一个删除按钮,这就是我得到的错误。

标签: javascript

解决方案


这就是它被要求完成的方式。我发现它超出了我的知识范围,但如果有人是古玩,我想我可以分享它。

const commentsUrl = "http://localhost:8080/comments";

let comments = [];

function getComments() {
  fetch(commentsUrl, { method: "GET" })
    .then((res) => res.json())
    .then((data) => {
      comments = data;
      renderComments(comments);
    });
}

const renderComments = (comments) => {
  const commentsContainer = document.getElementById("content");
  commentsContainer.innerHTML = "";
  comments.forEach(function (post) {
    const comment = document.createElement("div");
    comment.innerHTML = `
        <div id=${post.id} class="card">
            <div class="card text-center bg-info" style="width: 18rem;">
                <div class="card-body ">
                <h5 class="card-user ">${post.user}</h5>
                <h6 class="card-id mb-2 text-muted">Id: ${post.id}</h6>
                <p class="card-content">"${post.content}" </p>
                <p class="card-date">${post.date}<p>
                <button type="button" class="btn btn-primary btn-sm">Edit</button>
                <button type="button" class="btn btn-danger btn-sm" id="deleteBtn" onclick='remove(${post.id})'>Delete</button>
                
                </div>
            </div>
        </div>`;

    commentsContainer.append(comment);
  });
};

function remove(id) {
  fetch(`${commentsUrl}/${id}`, { method: "DELETE" }).then((comment) => {
    const index = comments.findIndex(
      (currentComment) => currentComment.id === comment.id
    );
    comments.splice(index - 1, 1);
    renderComments(comments);
  });
} 

getComments();

推荐阅读