javascript - 我尝试过此控制台问题。 TypeError : Failed to execute 'appendChild' on 'Node' : parameter 1 is not of type 'Node'

标签 javascript ajax dom error-handling axios

i dont understand where i miss-tack when i run this code show the error in console ( TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. ) can you tell me how can i solve this problem ?


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");
}

最佳答案

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

关于javascript - 我尝试过此控制台问题。 TypeError : Failed to execute 'appendChild' on 'Node' : parameter 1 is not of type 'Node' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54793870/

相关文章:

javascript - 数据加入d3;我一定没有正确理解选择和/或数据键功能

javascript - AngularJS 函数未定义

JavaScript 函数无法在外部文件中运行

javascript - 用addEventListener添加一个元素并在下一次迭代中获取它

javascript - 从基本提供者继承时如何防止直接访问属性?

javascript - 数据集与 .data - 区别?

javascript - 使用 jQuery 更新文本框

javascript - AJAX 数据返回和动态更改元素

ruby-on-rails - Ajax 调用丢失 session - Ruby on Rails/Radiant CMS 站点

javascript - 防止innerHTML属性中的XSS