我返回 HTML,我需要将其附加到页面上的元素,但它不是类型节点,是否可以转换它?
generateOptionMonths()
方法的代码最初位于 createCheckpointModalHtml()
中,一切正常,但整个代码非常复杂,所以我想将其作为单独的代码来执行方法。
我不明白为什么它不起作用,考虑到它与 createCheckpointModalHtml()
中的代码完全相同并且工作正常。
class CheckpointsArea {
constructor(){
this.monthsNames = this.generateOptionMonths();
}
createCheckpointModalHtml(){
let chooseMonth = createElement("select", "select-month");
chooseMonth.appendChild(this.monthsNames);//Error is here
}
generateOptionMonths(){
let monthNames = this.getDaysAndMonth().map( date => {
let month = createElement("option", "select-option");
month.innerText = date.Name;
return month
});
}
}
Error: Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
最佳答案
我可以像这样修复你的代码
<html>
<head></head>
<body></body>
<script>
class CheckpointsArea {
constructor(){
this.monthsNames = this.generateOptionMonths();
console.log(this.monthsNames);
this.createCheckpointModalHtml();
}
getDaysAndMonth() {
return [{Name: 'foo'}, {Name: 'bar'}];
}
createCheckpointModalHtml(){
let chooseMonth = document.createElement("select", "select-month");
this.monthsNames.forEach(m => chooseMonth.appendChild(m));
document.body.appendChild(chooseMonth);
}
generateOptionMonths(){
return this.getDaysAndMonth().map( date => {
let month = document.createElement("option", "select-option");
month.innerText = date.Name;
return month;
});
}
}
const cp = new CheckpointsArea();
</script>
</html>
您有 2 个主要问题。
您试图调用appendChild传递一个数组。相反,循环遍历数组并附加每个元素。
generateOptionMonths
没有返回任何内容。 map 函数中的 lambda 是,但函数本身不是。
您也没有将 select 元素附加到文档正文。
关于javascript - 是否可以将 html 转换为 Node 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811801/