簡體   English   中英

Javascript Web 組件 - 將 function 添加到 shadow-DOM

[英]Javascript Web-Components - Add function to the shadow-DOM

我正在為我的站點開發新的 Web 組件,這些組件僅適用於 html/css。 但是,我無法向我的影子 DOM添加某種 javascript 功能

在我的例子中,它是關於組件內的一個按鈕,它應該觸發一個 function 處理事件。 盡管如此,我總是收到 function 未定義的錯誤。 我知道影子 DOM 應該保護內部,但我不知道如何正確實現我的 js。 希望你能幫忙:)

class InfoSmall extends HTMLElement {
// attributes
constructor() {
  super();
  // not important
}

// component attributes
static get observedAttributes() {
  return [''];
}

// attribute change
attributeChangedCallback(property, oldValue, newValue) {
  if (oldValue == newValue) return;
  this[ property ] = newValue;
};

connectedCallback() {
  const shadow = this.attachShadow({ mode: 'open' });

  shadow.innerHTML = `
  <div class="container>
     <button id="copy"></button>
  </div>`

  shadow.querySelector('#copy').addEventListener("click", function () {
    // functionality
  });
}
}

我也嘗試了onclick-attribute但它對我來說是一樣的:沒有定義 function 。 或者我也嘗試用 HTML 標簽在 innerHTML 中編寫腳本......

您正在創建無效的 HTML,因為您在class="container>上缺少雙引號

您的代碼可以濃縮為:

 <script> customElements.define("my-element", class extends HTMLElement { constructor() { super() // sets AND returns 'this' scope.attachShadow({mode: 'open'}) // sets AND returns this.shadowRoot.innerHTML = `<div class="container"> <button>Click Me;</button> </div>`. this.shadowRoot.querySelector('button');onclick = () => { alert("YEAH;") }; } }); </script> <my-element></my-element>

暫無
暫無

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

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