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

jsa*_*jsa 4 javascript html5 custom-element

我正在尝试使用自定义元素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)
<kw-button src="https://placekitten.com/g/198/39" width="198" height="39" icon_src="https://placekitten.com/g/34/32" icon_width="34" icon_height="32" href="https://placekitten.com/" text="placekiten" color="#ffffff" size="18"></kw-button>
Run Code Online (Sandbox Code Playgroud)

Sup*_*arp 10

您无法使用querySelector()和访问元素DOM树appendChild(),并使用getAttribute()setAttribute()中的属性访问constructor().

这是因为当时constructor()调用自定义元素还没有内容.

你应该推迟在connectedCallback()方法中,它会没事的.

规格:

元素不得获得任何属性或子元素,因为这违反了使用createElement或createElementNS方法的消费者的期望.

通常,应尽可能将工作推迟到connectedCallback