javascript - 在 innerhtml 上使用 getElementbyid# 方法的 polymer

标签 javascript arrays polymer

我正在尝试检索通过 inside-h-t-m-l 加载的文本中各种元素的属性,但我无法仅获取一个特定元素。

这是我的代码:

<template>

<iron-ajax
      auto
      url="[[some/path/url.html]]"
      handle-as="text"
      last-response="{{inputText}}"></iron-ajax>

<div class="textcontent" inner-h-t-m-l="{{inputText}}"></div>
</template>
<script>
    Polymer({
      is: 'text-page',

      ready: function() {
        var test = document.getElementsByClassName("author");
        console.log(test);
      }
    });
</script>

所以我对此有两个问题:

  1. 这是将 html 页面加载到 Polymer 元素中的最佳方式吗?
  2. console.log 的输出是一个如下所示的数组:
HTMLCollection[0]
0: span.author
1: span.author
2: span.author
length: 3
__proto__: HTMLCollection

这是正确的,有 3 个元素的类名为“author”。但是,当我对 console.log(test[0]) 执行相同的操作以获取第一个时,我得到“undefined”作为输出。如何获取第一个,更重要的是该 span 的值?

最佳答案

  1. 是的,我个人认为这是将 HTML 加载到 Polymer 元素的最佳方法,除非您可以使用 HTML import作为正常的方式来做到这一点。

  2. 使用 getElementsByClassName 您将获得一个 HTML 集合,并且您无法直接访问这些元素的值。 您可以使用不同的方法将其作为数组获取,例如 Array.fromfor...of loop 。 另一种解决方案可能是使用简单的 this.querySelectorAll() 将它们作为数组获取。

澄清here (StackOverflow answer)here (Medium article)

const html = `<span class="author">test</span><span class="author">another</span>`
addEventListener('WebComponentsReady', function() {

  Polymer({
    is: 'x-example',
    properties: {
      html: {
        type: String,
        value: html
      }
    },

    ready: function() {
      // 1° solution
      const test = this.getElementsByClassName('author');
      const first = Array.from(test)[0];
      console.log('First element innerText --->', first.innerText);

      // Or you can simply loop on the array
      Array.from(test).forEach(item => console.log(item.innerText));

      // 2° solution
      const test2 = this.querySelectorAll('.author');
      test2.forEach(item => console.log(item.innerText));
    }
  });
});
body {
  font-family: sans-serif;
}
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">

<dom-module id="x-example">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>

    <h1>polyfiddle</h1>
    <div inner-H-T-M-L="[[html]]">
    </div>
  </template>
</dom-module>

<x-example></x-example>

关于javascript - 在 innerhtml 上使用 getElementbyid# 方法的 polymer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43626503/

相关文章:

html - Polymer 1.0 一次导入所有元素

css - 带有 :host in styles has no affect 的 Polymer @import 主题文件

php - 获取特定索引和列处的数组值

javascript - 基于字符串数组过滤对象数组 "with partial match"

javascript - 使用 reverse() javascript 求和两个最高值

polymer - 从 Polymer 对象属性值设置属性

javascript - node.js 中不同的 module.exports 模式

javascript - 如何使用 JavaScript 修改 CSS 类?

javascript - 在溢出div的水平滚动上,填充进度条

javascript - 如果带有 && 优先级的条件不起作用