相关疑难解决方法(0)

无法从其构造函数访问自定义元素的属性

我正在尝试使用自定义元素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)

javascript html5 custom-element

4
推荐指数
1
解决办法
700
查看次数

标签 统计

custom-element ×1

html5 ×1

javascript ×1