[英]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.我正在尝试使自定义 shadow dom 元素从存储在 components 文件夹中的 HTML 文件中获取其 HTML。 I can get the HTML just fine like this
我可以像这样得到 HTML
$.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但是如果我然后尝试这样做以将 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);
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.我收到一个错误
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
我已经在许多不同的配置中尝试过它,但无法让它工作。 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 . this
自己的函数中function(data) {...}
回调是不一样this
是一个在constructor()
因为的关闭。
You should save the original reference in another variable (ie that
, or here: elem
).您应该将原始引用保存在另一个变量中(即
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.