繁体   English   中英

将 ajax 调用中的 html 附加到 shadow DOM

[英]attaching html from ajax call to shadow DOM

我正在尝试使自定义 shadow dom 元素从存储在 components 文件夹中的 HTML 文件中获取其 HTML。 我可以像这样得到 HTML

$.get( "/component/miniPlayer.html", function( data ) {
    console.log(data)
    root.innerHTML = data;
});

但是如果我然后尝试这样做以将 HTML 放在自定义元素中

class miniPlayer extends HTMLElement{
    constructor(){
        super();

        this._root = this.attachShadow({mode: 'open'});
        this._root.innerHTML = 

        $.get( "/component/miniPlayer.html", function( data ) {
            console.log(data)
            this._root.innerHTML = data;
        });
    }
}

window.customElements.define('mini-player', miniPlayer);

我收到一个错误Uncaught TypeError: Cannot set property 'innerHTML' of undefined我已经在许多不同的配置中尝试过它,但无法让它工作。 这是可能的,还是我将不得不尝试其他的东西

this自己的函数中function(data) {...}回调是不一样this是一个在constructor()因为的关闭

您应该将原始引用保存在另一个变量中(即that ,或此处: elem )。

class miniPlayer extends HTMLElement{
    constructor(){
        super();

        this._root = this.attachShadow({mode: 'open'});
        this._root.innerHTML = 

        var elem = this
        $.get( "/component/miniPlayer.html", function( data ) {
            console.log(data)
            elem._root.innerHTML = data;
        });
    }
}

window.customElements.define('mini-player', miniPlayer);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM