【问题标题】:Cannot get element by id in Polymer 2在 Polymer 2 中无法通过 id 获取元素
【发布时间】:2019-10-05 11:40:17
【问题描述】:

在函数的dom-repeat 中获取 HTML 元素时遇到问题。

一开始我有这段代码,它工作正常。

HTML:

<div class="card">
  <app-toolbar>
    <paper-button on-click="downloadTable">[[localize('Download')]]</paper-button>
  </app-toolbar>
  <table id="table" noshadow>
  <!--Table content here-->
  </table>
</div>

JS:

downloadTable() {
    this.tableToExcel(this.$.table, 'table.xls');
}

但后来我从一个表转到多个表,这些表使用dom-repeat 进行迭代。

HTML:

<template id="tablesRoot" is="dom-repeat" items="[[tables]]" as="table">
    <div class="card">
      <app-toolbar>
        <paper-button on-click="downloadTable">[[localize('Download')]]</paper-button>
      </app-toolbar>
      <table id={{table.elId}} noshadow>
      <!--elId is a string: table0, table1, table2, ... Table content here-->
      </table>
    </div>
</template>

JS:

downloadTable() {
    this.tableToExcel(this.$.table0, 'table.xls');
    //Trying to get the first table. Also tried without success:
    //this.$.tablesRoot.table0
    //this.$.tablesRoot.$.table0
}

似乎在元素检查器中,为tabledom-repeat 添加了正确的ID。但仍然无法访问任何table。我需要怎么做?

【问题讨论】:

    标签: javascript html polymer getelementbyid polymer-2.x


    【解决方案1】:

    看来,您无法像这样处理动态创建的元素。相反,您必须使用:

    Polymer.dom(this.root).querySelector('#table0')
    

    【讨论】:

    • 您也可以拨打this.shadowRoot.querySelector('#table0')
    【解决方案2】:

    你也可以调用

    this.$$('#table0')
    

    这是Polymer.dom(this.root).querySelector('#table0')的简写,如图here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      相关资源
      最近更新 更多