簡體   English   中英

如何從類中訪問自定義元素的下一個同級?

[英]How to access the next sibling of the custom element from within the class?

在Web組件中,我有一個自定義元素,並且我想訪問下一個同級元素。 我怎樣才能做到這一點? 我有這個

class DomElement extends HTMLElement {
    constructor() {
        super();
        let shadowRoot = this.attachShadow({mode: 'open'});
        const t = document.currentScript.ownerDocument.querySelector('#x-foo-from-template');
        const instance = t.content.cloneNode(true);
        shadowRoot.appendChild(instance);
    }

    fixContentTop() {
        var sibling = this.nextElementSibling;
        if (sibling) {

        }
    }
}

sibling變為空。

Des有人知道怎么做嗎?

謝謝

實際上,在調用this.nextElementSibling的方法中, this確實表示具有同級元素的自定義元素。

它在此示例中有效,因為感謝arrow函數,它引用了自定義元素:

 customElements.define('dom-elem', class extends HTMLElement { constructor() { super() var sh = this.attachShadow({mode: 'open'}) sh.appendChild(document.querySelector('template').content.cloneNode(true)) sh.querySelector('button').onclick = () => console.log('sibling = %s', this.nextElementSibling.localName) } }) 
 <dom-elem></dom-elem> <dom-elem></dom-elem> <template> <button>Get Sibling</button> </template> 

如果使用function ()語法,則它將引用<button> ,因此不會返回任何同級元素:

 customElements.define('dom-elem', class extends HTMLElement { constructor() { super() var sh = this.attachShadow({mode: 'open'}) sh.appendChild(document.querySelector('template').content.cloneNode(true)) sh.querySelector('button').onclick = function () { console.log('sibling = %s', this.nextElementSibling) } } }) 
 <dom-elem></dom-elem> <dom-elem></dom-elem> <template> <button>Get Sibling</button> </template> 

暫無
暫無

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

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