如何使用 javascript 创建自定义 HTML 元素?

How to create a custom HTML element using javascript?

我希望能够创建一个可以显示 cookie 值的自定义 HTML 元素,以便我可以轻松地将 cookie 值插入到我的文档中。 到目前为止我的代码是:

var cNum = 0;

customElements.define('get-cookie', getC);

class getC extends HTMLElement {
  constructor() {
    super();

    cNum++;
    var cName = this.getAttribute('cName');
    this.setAttribute('id', cName + cNum);
    var currentE = document.getElementById(cName + cNum);
    var cValue = 'Oops! We have run into a problem';
    if (this.hasAttribute('cName')) {
      cValue = getCookie(this.getAttribute('img'));
    }
    var outC = document.createElement('a');
    outC.innerHTML = cValue;
    currentE.appendChild(outC);
  }
}

<p>
  Current User: <get-cookie cName="currentUSR" ></get-cookie>
</p>

但是当我在 firefox 上 运行 时出现这个错误:

ReferenceError: can't access lexical declaration `getC' before initialization (myfile.js:4:1)

此外:我的 jQuery 知识为零,如果我能远离它,我会更愿意。

非常感谢所有帮助!谢谢!

编辑:我忘了补充一点,我已经在代码的其他地方定义了 getCookie() 函数。

customElements.define('get-cookie', getC); 应该在底部,在你实际定义了 class.

之后

在 class 定义之后保留它应该可以修复它:

var cNum = 0;

class getC extends HTMLElement {
  constructor() {
    super();

    cNum++;
    var cName = this.getAttribute('cName');
    this.setAttribute('id', cName + cNum);
    var currentE = document.getElementById(cName + cNum);
    var cValue = 'Oops! We have run into a problem';
    if (this.hasAttribute('cName')) {
      cValue = this.getCookie(this.getAttribute('img'));
    }
    var outC = document.createElement('a');
    outC.innerHTML = cValue;
    currentE.appendChild(outC);
  }

  getCookie() {
    return 'John Doe';
  }
}

customElements.define('get-cookie', getC);
<p>Current User:
  <get-cookie cName="currentUSR"></get-cookie>
</p>

我也不确定这里的 getCookie 是什么。所以我在 class 上创建了一个名为 getCookie 的方法,现在我在 constructor 中用 this 关键字使用它。