2014-08-29 47 views
3

我有一個form-el誰只是一個容器誰必須包裝所有兒童在div與特定的類。我不想在每個表單元素中重複這個div,而是想讓from-el包裝它們。 我可以遍歷所有元素並將它們包裹在其他html標籤中嗎?實現這一裝飾元素從<content>

// Markup 
<form-el> 
    <input-el label="name" type="text" /> 
    <span>This must also be wrapped</span> 
</form-el> 

// Would produce 
<form> 
    <div class="form-field"> 
     <label>name</label> 
     <input type="text" name="name" /> 
    </div> 
    <div class="form-field"> 
     <span>This must also be wrapped</span> 
    </div> 
</form> 
// Where '<div class="form-field">' is produced by 'from-el' 

回答

5

一種方式是通過模板重複適合你的光-DOM節點<content>,像這樣:

<polymer-element name="form-el"> 
<template> 

    <template repeat="{{wrappers}}"> 
    <div style="border: 2px solid orange; padding: 2px; margin: 4px"> 
     <content select="[key='{{}}']"> 
    </div> 
    </template> 

</template> 
<script> 

    Polymer({ 
    domReady: function() { 
     this.updateWrappers(); 
    }, 
    updateWrappers: function() { 
     this.wrappers = []; 
     for (var i=0, n=this.firstChild; n; n=n.nextSibling) { 
     if (n.setAttribute) { 
      // attach a selectable key to each light-dom node 
      n.setAttribute('key', i); 
      // specify a <content> with that key 
      this.wrappers.push(i++); 
     } 
     } 
    } 
    }); 

</script> 
</polymer-element> 

http://jsbin.com/mukip/5/edit

+0

非常感謝。但是當我嘗試包裹聚合物元素時,它只顯示第一個。 http://jsbin.com/sadexakoyuco/1/edit – 2014-09-02 08:41:37

+0

沒有自定義元素可以是無效的,喵喵,你不能使用''你必須使用''。 – 2014-09-02 19:05:23

+0

@ScottMiles如何/何時可以得到包裝?由於模板是異步標記和分佈的,因此''this.updateWrappers();''很簡單''setTimeout'足夠後,我無法立即獲得對this.shadowRoot.querySelectorAll(「div」)的引用? 在簡化的情況下,它的工作原理是http://jsbin.com/zuxiqo/1/edit,但它足以避免任何競爭條件嗎? – tomalec 2015-02-24 00:55:54