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

3

我希望能够创建自定义的HTML元素,以便显示cookie的值,这样我就可以轻松地将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()函数已在我的代码中定义。
1个回答

1

customElements.define('get-cookie', getC); 应该放在底部,在您实际定义类之后。

将其放在类定义之后应该可以解决问题:

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 是什么。所以我在该类上创建了一个名为 getCookie 的方法,现在我正在使用它与 this 关键字一起在 constructor 中。


这对我有用。在我的问题中,我忘记提到我在代码的另一个部分定义了getCookie()函数,所以我将那部分改回了原来的样子,但是将customElements.define更改为底部就可以了。谢谢! - jkrei0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接