我正在尝试使用自定义元素API为游戏中的浏览器引擎用于显示按钮和类似的自定义元素创建各种填充.但是,我似乎无法从构造函数中访问元素的属性(例如,src,href ...).
这是一个例子:
class KWButton extends HTMLElement {
constructor() {
super();
var attributes = this.attributes;
var shadow = this.attachShadow({
mode: 'open'
});
var img = document.createElement('img');
img.alt = this.getAttribute('text'); // the getAttribute call returns null
img.src = this.getAttribute('src'); // as does this one
img.width = this.getAttribute('width'); // and this
img.height = this.getAttribute('height'); // and this
img.className = 'vivacity-kwbutton'; // this works fine
shadow.appendChild(img);
img.addEventListener('click', () => {
window.location = this.getAttribute('href'); // this works perfectly fine
});
}
}
customElements.define('kw-button',
KWButton); …Run Code Online (Sandbox Code Playgroud)