2014-08-29 42 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