我返回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
});
}
}
错误:未捕获类型错误:未能在"Node"上执行"appendChild":参数1的类型不是"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>
你有两个主要问题。
您试图调用传递数组的appendChild。相反,在数组上循环并附加每个元素。
generateOptionMonths
没有返回任何内容。映射函数中的lambda为,但函数本身不是。
您也没有将select元素追加到文档正文中。