Javascript:在自定义元素上使用自定义属性时,getAttribute引发意外的标识符[关闭]

问题描述 投票:0回答:1

我在此代码的第10行不断收到错误,该行在其中定义Var x表示它是未识别的标识符。我正在尝试创建自己的自定义元素。当该自定义元素位于HTML中并具有国家/地区代码时,控制台将记录此代码。但是由于某种原因,它不起作用。你能帮我吗?谢谢!

class FlagIcon extends HTMLElement {
  constructor() {
    super();
    this._countryCode = null;
  }

  static get observedAttributes() {
    return ["country"];
  }

  var x = this.getAttribute("country");
  console.log(x);

}

customElements.define("flag-icon", FlagIcon);
<flag-icon country="hi">Hello</flag-icon>
javascript html custom-attributes custom-element getattribute
1个回答
0
投票

Info:

创建元素时调用constructor()。

connectedCallback()在元素附加到DOM后被调用。

参考:https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements

尝试运行此代码段

<script> class FlagIcon extends HTMLElement { constructor() { super(); this._countryCode = null; } connectedCallback(){ var x = this.getAttribute("country"); console.log(x); } static get observedAttributes() { return ["country"]; } } customElements.define("flag-icon", FlagIcon); </script> <html> <flag-icon country="hi">Hello</flag-icon> </html>
© www.soinside.com 2019 - 2024. All rights reserved.