2017-04-26 57 views
0

我試圖在通過inner-h-t-m-l加載的文本中檢索各種元素上的屬性,但是我無法獲得僅僅一個特定元素。聚合物使用getElementsby#方法在內部-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頁面加載到聚合物元件的最佳方式?
  2. 所述的console.log的輸出是一個數組,看起來像這樣:
HTMLCollection[0] 
0: span.author 
1: span.author 
2: span.author 
length: 3 
__proto__: HTMLCollection 

這是正確的,有與類名「作者」 3個元素。但是,當我用console.log(test[0])做同樣的事情,以獲得第一個,我得到"undefined"作爲輸出。我怎樣才能得到第一個,更重要的是,這個價值span

回答

1
  1. 是的,我個人認爲這是HTML加載到聚合物元件,除非你可以使用HTML import正常的方式來做到這一點的最好辦法。

  2. With getElementsByClassName您將得到一個HTML collection,您無法直接訪問這些元素的值。 您可以使用不同的方法將其作爲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>

+0

如果我使用'Array.from'它給我回一個空數組。如果我在上面的代碼中使用了'console.log(test.length)',它也會讓我回到'0'。 – Vims

+0

下面是一個工作示例(儘管沒有'iron-ajax'),請打開控制檯查看結果:https://jsfiddle.net/uq34vk2z/ – LasaleFamine

+0

謝謝!這工作沒有鐵ajax,但當我添加如果失敗的鐵ajax。經過一番搜索之後,我發現它一定是因爲函數在文本加載之前被調用,所以'first'是'undefined'。所以我添加了一個'if(first!== undefined)',然後它工作得很好。 – Vims