[英]Accessing child element with JQuery in connectedCallback (Web Compoenent)
我有一個非常簡單的 Web 組件,如下所示,它從服務器加載組件模板文件:
export default class EditorComponent extends HTMLElement {
async connectedCallback() {
let file = "http://blog/components/editor/editor.html";
let res = await fetch( file );
this.attachShadow( { mode: 'open' } ).innerHTML = await res.text();
}
}
customElements.define('editor-component', EditorComponent);
我需要通過 jQuery 訪問組件 HTML 文件中的子元素。 我嘗試了以下但無濟於事:
async connectedCallback() {
let file = "http://blog/components/editor/editor.html";
let res = await fetch( file );
this.attachShadow( { mode: 'open' } ).innerHTML = await res.text();
$(this).find('div').hide(); <<<<< WHAT I AM ATTEMPTING
}
我還添加了超時,但這也沒有幫助。
這能做到嗎?
你必須自己做 jQuery 語法
我在這里做普通的標准 JS 選擇器
因為我在 2011 年IE9 發布時忘記了 jQuery 選擇器(需要 80KB+ 的庫)...
加載HTML,在shadowDOM中顯示有點生硬,
然后只提取你想要的內容。 見下面的h1
標准DOMParser()
可以分擔工作,速度更快,因為沒有 HTML 被渲染,
見alink
:
<web-component></web-component> <script> customElements.define("web-component", class extends HTMLElement { async connectedCallback() { let file = "https://load-file.github.io/"; let html = await (await fetch(file)).text(); // Browser engine parses HTML to visual (shadow)DOM this.attachShadow({mode: 'open'}).innerHTML = html; let h1 = this.shadowRoot.querySelector("h1"); // Browser engine parses HTML in Memory let doc = new DOMParser().parseFromString(html, "text/html"); let alink = doc.querySelector("h2 a"); alink.target = "blank" ; this.shadowRoot.replaceChildren(h1, "SHIFT+Click this link: ", alink); } }) </script>
閱讀以下所有方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.