我正在尝试检索通过 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>
所以我对此有两个问题:
- 这是将 html 页面加载到 Polymer 元素中的最佳方式吗?
- 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
的值?
最佳答案
是的,我个人认为这是将 HTML 加载到 Polymer 元素的最佳方法,除非您可以使用 HTML import作为正常的方式来做到这一点。
使用
getElementsByClassName
您将获得一个HTML 集合
,并且您无法直接访问这些元素的值。 您可以使用不同的方法将其作为数组获取,例如 Array.from或 for...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/