javascript - 我试过这个控制台问题。TypeError:无法在“Node”上执行“appendChild”:参数 1 不是“Node”类型
问题描述
我不明白当我运行此代码时我错过了哪里在控制台中显示错误(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");
}
解决方案
perentElement.appendChild("tr");
并将tdAction.appendChild("deleteBtn")
尝试将字符串“tr”和“deleteButton”作为子项添加到perentElement
/ tdAction
。因为字符串不是NodeElement
s,所以您会收到此错误。您不能使用appendChild()
方法将字符串作为子项附加到 DOM 元素。
在这里进一步阅读:https ://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild#Returns
推荐阅读
- nativescript - Nativescript + Angular:iOS模拟器多次触发点击事件
- javascript - 在调试 React 时找出谁在渲染组件
- git-bash - 我的身份验证第一次失败后如何要求 Gitbash 再次对我进行身份验证?
- android - 更新到 Android API 28 后,Espresso 测试失败
- hive - 无法从联接中获取我想要的所有数据
- f# - 如何将度量定义为另一个度量的倍数
- django - 将 Django 项目从生产迁移到本地 SQL 服务器
- java - JHipster - 如何添加另一个连接到第二个数据库(例如 MySQL)
- python-3.x - 如何检查嵌套列表是否存在,如果存在则不嵌套?
- r - 绘制每个 k-means 集群的热图?