javascript - 是否可以将 html 转换为 Node 类型?

标签 javascript

我返回 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 个主要问题。

  1. 您试图调用appendChild传递一个数组。相反,循环遍历数组并附加每个元素。

  2. generateOptionMonths 没有返回任何内容。 map 函数中的 lambda 是,但函数本身不是。

您也没有将 select 元素附加到文档正文。

关于javascript - 是否可以将 html 转换为 Node 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811801/

相关文章:

javascript - 有没有办法将长度大于 15 的字符串转换为数字,而不进行四舍五入?

javascript - Canvas 中的 HTML5 图像适配问题

javascript - 如何使用计时器关闭模态窗口

JavaScript "classes"

javascript - HTML5 Canvas 的环绕 : How to Get (Static) Shapes to Continue around Edges of Canvas

php - 从数据库表中获取值到选择框中

javascript - 同一页面上的多个脚本版本 (d3.js)

javascript - 如何忽略javascript中的事件?

javascript - 如何从一组日期中获取最新日期? - JavaScript/ typescript

javascript - 在页面上设置 iframe