简体   繁体   中英

attaching html from ajax call to shadow DOM

I am trying to make a custom shadow dom element get its HTML from an HTML file stored in a components folder. I can get the HTML just fine like this

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

but if I then try to do this to put the HTML in the custom element

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);

I get an error Uncaught TypeError: Cannot set property 'innerHTML' of undefined I have tried it in many different configurations but can't get it to work. is this possible or am i going to have to try something else

this inside your function function(data) {...} callback is not the same this that the one in the constructor() because of the closure .

You should save the original reference in another variable (ie that , or here: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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