我尝试过此控制台问题。 TypeError:无法在“节点”上执行“ appendChild”:参数1不是“节点”类型

时间:2019-02-20 19:25:58

标签: javascript ajax dom error-handling axios

  

我不明白我在运行此代码时在哪里错处显示控制台中的错误(TypeError:无法在“ Node”上执行“ appendChild”:参数1的类型不是“ Node”。   )你能告诉我如何解决这个问题吗?

import axios from "axios";

const BASE_url = "  http://localhost:3000/contacts";

window.onload = () => {
  const mytbody = document.querySelector("#mytbody");
  axios
    .get(BASE_url)
    .then(res => {
      res.data.forEach(function(contact) {
        createTDelement(contact, mytbody);
      });
    })
    .catch(err => console.log(err));
};

function createTDelement(contact, perentElement) {
  const tr = document.createElement("tr");

  const tdId = document.createElement("td");
  tdId.innerHTML = contact.tdId;
  tr.appendChild(tdId);

  var tdName = document.createElement("td");
  tdName.innerHTML = contact.name;
  tr.appendChild(tdName);

  const tdEmail = document.createElement("td");
  tdEmail.innerHTML = contact.email;
  tr.appendChild(tdEmail);

  const tdPhone = document.createElement("td");
  tdPhone.innerHTML = contact.phone ? contact.phone : "N/A";
  tr.appendChild(tdPhone);

  const tdAction = document.createElement("td");

  const editBtn = document.createElement("button");
  editBtn.className = "btn btn-warning";
  editBtn.innerHTML = "Edit";
  editBtn.addEventListener("click", () => {
    console.log("i am editable");
  });
  tdAction.appendChild(editBtn);

  const deleteBtn = document.createElement("button");
  deleteBtn.className = "btn btn-danger";
  deleteBtn.innerHTML = "Delete";
  deleteBtn.addEventListener("click", () => {
    console.log("i am editable");
  });
  tdAction.appendChild("deleteBtn");

  perentElement.appendChild("tr");
}

1 个答案:

答案 0 :(得分:0)

perentElement.appendChild("tr");tdAction.appendChild("deleteBtn")将尝试将字符串“ tr”和“ deleteButton”作为子元素添加到perentElement / tdAction中。由于字符串不是NodeElement,因此会收到此错误。您不能使用appendChild()方法将字符串作为子元素附加到DOM元素。

在此处进一步阅读:https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild#Returns