簡體   English   中英

如何使用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:在初始化之前無法訪問詞法聲明`getC'(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關鍵字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM