Javascript ES6类问题

Javascript ES6类问题,javascript,ecmascript-6,Javascript,Ecmascript 6,我是ECMA6的新手。我有两个类-myApp.js和一个简单的Image.js类。 我试图在App.js中创建一个空的div,并将该div id传递给image类以附加一个img src。 在Image.js 有什么想法吗 App.js class KK_App{ constructor(src, width, height){ this._imgdiv = document.createElement('div'); thi

我是ECMA6的新手。我有两个类-my
App.js
和一个简单的
Image.js
类。
我试图在
App.js
中创建一个空的
div
,并将该div id传递给image类以附加一个img src。
Image.js

有什么想法吗

App.js

 class KK_App{

        constructor(src, width, height){

            this._imgdiv = document.createElement('div');
            this._imgdiv.setAttribute('id', 'posterphoto');

            var newpic = new KK_Image('poster_outlines2.png', 240, 250, this._imgdiv);
            newpic.draw();

        }

    }
KK_Image.js

class KK_Image{

    constructor(src, width, height, parent){
        this._src = src;
        this._width = width;
        this._height = height;
        this._parent = parent;
        this._parentid = this._parent.getAttribute('id');
    }

    draw(){
        console.log( this._parentid );
        const markup = `<img src='${this._src}' width='${this._width}' height='${this._height}'></img>`;
        document.getElementById(${this._parentid}).innerHTML = markup;

         //it dies here saying ${this._parentid} is null
         //it works if I pass the id of a div that is already loaded into the dom in html

    }

}
类KK_图像{ 构造函数(src、宽度、高度、父级){ 这个._src=src; 这个。_宽度=宽度; 这个。_高度=高度; 这个。_parent=parent; this.\u parentid=this.\u parent.getAttribute('id'); } 画(){ console.log(this.\u parentid); 常量标记=``; document.getElementById(${this.\u parentid}).innerHTML=标记; //它死在这里说${this.\u parentid}为空 //如果我传递一个已经在html中加载到dom中的div的id,它就会工作 } }
当您执行此操作时。_imgdiv=document.createElement('div')-这仅创建一个元素

您还需要将其附加到页面中,例如:

document.body.appendChild(this._imgdiv)

执行
document.getElementById时(…
元素必须在页面中才能找到。

看起来您只创建了元素,但没有将其添加到任何地方。在
KK_应用程序中创建新元素并分配给实例属性。然后在类
KK_Image
中,您期望该文档将包含您的元素-这种假设是错误的,因为您从未添加过元素要记录的元素

为此,您必须使用例如
appendChild
函数

正确的解决方案应如下所示:

class KK_App{
    constructor(src, width, height){

        this._imgdiv = document.createElement('div');
        this._imgdiv.setAttribute('id', 'posterphoto');
        document.body.appendChild(this._imgdiv); // <- HERE
        var newpic = new KK_Image('poster_outlines2.png', 240, 250, this._imgdiv);
        newpic.draw();

    }

}
KK_类应用程序{
建造商(src、宽度、高度){
这个._imgdiv=document.createElement('div');
这个.u imgdiv.setAttribute('id','posterphoto');

document.body.appendChild(this.\u imgdiv);//
如果我传递一个已经加载到dom中的div的id,它就会工作。
-这就是
getElementById
的工作原理,它无法获取dom中没有的内容。有关更多详细信息,请参阅。您的元素只会被创建,而不会在页面中,您需要将其附加在一起。为什么不将图像作为实际元素创建,然后将其附加到t他使用DOM appendChild方法进行div?