我有一個非常簡單的 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
}
我還添加了超時,但這也沒有幫助。
這能做到嗎?
uj5u.com熱心網友回復:
你必須自己做 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>
閱讀以下所有方法:
- https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/343476.html
標籤:javascript 查询 网络组件
