通过querySelectorAll()获取节点列表 [英] Getting a node list by querySelectorAll()

查看:620
本文介绍了通过querySelectorAll()获取节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下示例代码:

import { LitElement, html, css } from 'lit-element';

class ItemsDisplay extends LitElement {

    static get styles() {...}
    static get properties {...}

    constructor () {
        super();
        ...
    }

    render {
        return html`
            ${this.items.map((item, index, array) => html`
                <div class="name">
                    ...
                </div>
            `)}        
        `;
    }
}

选择所有具有名称"类的节点的适当方法是什么?

What is the appropriate way to select all nodes with class "name"?

我尝试了以下方法,但是失败nodesList一直是undefined:

I have tried the following ways, but failed; all times nodesList was undefined:

  • constructor内部:
  this.nodesList = this.shadowRoot.querySelectorAll(".name");

  • 使用:
  •   firstUpdated(changedProperties) {
          return this.nodesList = this.shadowRoot.querySelectorAll(".name");
      }
    

    • 在自定义函数中:
    •   getNodesList() {
            let nodesList = this.shadowRoot.querySelectorAll(".name");
            ...
        }
      

      我也尝试过:

      connectedCallback() {
          super.connectedCallback();
          return this.nodesList = this.shadowRoot.querySelectorAll(".name");
      }
      

      期待阅读解决方案.

      Tia

      推荐答案

      您不应尝试访问构造函数中的DOM节点,因为它们尚不可用.

      You shouldn't try to access DOM node in the constructor, because they won't be available yet.

      查询DOM节点的最佳位置是firstUpdated()生命周期回调,该回调在第一次更新元素的DOM后调用.您也不需要从firstUpdated返回它,只需执行以下操作即可:

      The best place to query DOM nodes is the firstUpdated() lifecycle callback, which is called after the first time your element's DOM has been updated. You also don't need to return it from firstUpdated, you can just do something like:

        firstUpdated(changedProperties) {
          // Store a reference to the form element for easy access
          this.$someNode = this.shadowRoot.querySelector('div');
      

      您可以在以下位置看到一些示例: https://stackblitz. com/edit/open-wc-lit-demos?file = 02-intermediate%2F05-querying-dom.js

      You can see some examples of this over at: https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F05-querying-dom.js

      https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F01-first-updated.js

      此外,如果您使用的是TypeScript,则可以使用query装饰器:

      Additionally, if you're using TypeScript, you can use the query decorator:

      @query('div')
      myDiv;
      

      更多信息: https: //github.com/Polymer/lit-element/blob/master/src/test/lib/decorators_test.ts#L326

      这篇关于通过querySelectorAll()获取节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆