将 HTML 从 ajax 调用附加到影子 DOM



我正在尝试使自定义影子 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我已经在许多不同的配置中尝试过它,但无法让它工作。这可能吗,还是我将不得不尝试其他事情

函数function(data) {...}回调中的thisconstructor()中的回调this不同,因为闭包。

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

最新更新