【问题标题】:attaching html from ajax call to shadow DOM将 ajax 调用中的 html 附加到 shadow DOM
【发布时间】:2020-04-03 01:30:28
【问题描述】:

我正在尝试使自定义影子 dom 元素从存储在组件文件夹中的 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 我已经在许多不同的配置中尝试过它,但无法让它工作。这是可能的还是我必须尝试别的方法

【问题讨论】:

    标签: javascript ajax dom shadow-dom


    【解决方案1】:

    this 函数内的 function(data) {...} 回调与 constructor() 中的 this 不同,因为 closure

    您应该将原始引用保存在另一个变量中(即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);
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2020-11-25
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2020-10-17
      • 2011-11-11
      相关资源
      最近更新 更多