我希望能够创建一个可以显示 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);
应该在底部,在您实际定义类之后。
在类定义之后保留它应该可以修复它:
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
的方法,现在我在 constructor
中使用 this
关键字来使用它。
关于javascript - 如何使用 javascript 创建自定义 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326162/