如何使用javascript创建自定义HTML元素?
我希望能够创建一个自定义HTML元素,它可以显示cookie的值,这样我就可以轻松地将cookie值插入到文档中。 到目前为止,我的代码是:如何使用javascript创建自定义HTML元素?,javascript,html,element,web-component,Javascript,Html,Element,Web Component,我希望能够创建一个自定义HTML元素,它可以显示cookie的值,这样我就可以轻松地将cookie值插入到文档中。 到目前为止,我的代码是: var cNum = 0; customElements.define('get-cookie', getC); class getC extends HTMLElement { constructor() { super(); cNum++; var cName = this.getAttribute('cName');
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);
}
}
及
当前用户:
但当我在firefox上运行它时,会出现以下错误:
ReferenceError:无法在初始化之前访问词法声明“getC”(myfile.js:4:1)
另外:我没有jQuery知识,如果我能远离它,我会更愿意
非常感谢您的帮助!谢谢
编辑:我忘记添加我已经在代码的其他地方定义了getCookie()函数。
customElements.define('get-cookie',getC)在实际定义类之后,代码>应该位于底部
在类定义之后保留它应该可以修复它:
var cNum=0;
类getC扩展了HtmleElement{
构造函数(){
超级();
cNum++;
var cName=this.getAttribute('cName');
this.setAttribute('id',cName+cNum);
var currentE=document.getElementById(cName+cNum);
var cValue='Oops!我们遇到了一个问题';
if(this.hasAttribute('cName')){
cValue=this.getCookie(this.getAttribute('img'));
}
var outC=document.createElement('a');
outC.innerHTML=cValue;
当前附加子项(outC);
}
getCookie(){
返回“John Doe”;
}
}
定义('get-cookie',getC)代码>
当前用户:
这对我很有效。在我的问题中,我忘了提到我在代码的另一部分中定义了getCookie()函数,所以我将该部分更改回原来的部分,但将customElements.define更改到底部是可行的。谢谢
<p>
Current User: <get-cookie cName="currentUSR" ></get-cookie>
</p>