Javascript 当以编程方式创建HtmleElement时,我可以在构造函数之前设置属性吗?
我有这样的东西Javascript 当以编程方式创建HtmleElement时,我可以在构造函数之前设置属性吗?,javascript,web-component,Javascript,Web Component,我有这样的东西 class Thing extends HTMLElement{ constructor(){ super(); this.selected = this.getAttribute('selected'); ... } } this.things.forEach((thing)=>{ tabString += `<my-thing selected=${thing.selected}></my-thing>`;
class Thing extends HTMLElement{
constructor(){
super();
this.selected = this.getAttribute('selected');
...
}
}
this.things.forEach((thing)=>{
tabString += `<my-thing selected=${thing.selected}></my-thing>`;
});
this.things.forEach((thing)=>{
this.element.appendChild(new Thing());
});
当创建类似
的元素时,这种方法可以很好地工作。现在我想注入一个列表。我可以这样做
class Thing extends HTMLElement{
constructor(){
super();
this.selected = this.getAttribute('selected');
...
}
}
this.things.forEach((thing)=>{
tabString += `<my-thing selected=${thing.selected}></my-thing>`;
});
this.things.forEach((thing)=>{
this.element.appendChild(new Thing());
});
但是如何设置所选的
我仍然需要能够将组件添加为HTML中的普通标记,并且它应该以任意方式处理属性。一种方法是在构造函数中传递
selected
:
class Thing extends HTMLElement{
constructor(selected){
super();
this.selected = selected || this.getAttribute('selected');
...
}
}
那么,你是说直到元素被附加之后才运行构造函数?@JGleason在构造函数运行之前设置
selected
是否重要?这不是我想要的,我仍然希望能够从普通标记中的属性进行设置。这是如何处理的?@JGleason在创建元素后,代码将覆盖所选的
。我不认为有办法在创建元素之前设置属性。这很好,可能就是答案,没有办法。在实例化对象之前,不能设置对象的属性。没有什么可设置的属性。