将 HTML 附加到聚合物模板根
Appending HTML to polymer template root
我无法将动态 HTML 直接添加到聚合物元素,而是似乎被迫将其添加到现有的子元素。这是聚合物的限制,还是我缺乏理解?
虽然有另一个 div 肯定很受欢迎,但我真的希望聚合物能帮助我把它放在我的评论镜中。
例子
对于以下元素:
<polymer-element name="my-el1">
<template>
<div id='myid'></div>
</template>
</polymer-element>
此脚本仅在添加到 div (#myid) 而不是直接添加到模板时显示:
<script>
var el = document.createElement('div');
el.innerHTML = 'text';
this.appendChild(el); //shows in DOM, not in browser
this.$.myid.appendChild(el); //works
</script>
JSBIN
完整示例位于 jsbin
this
引用 Polymer 对象而不是实际的 DOM。为了直接在阴影中添加一些东西DOM,你需要使用以下内容:
this.shadowRoot.appendChild(el);
这是您的 JSBin:http://jsbin.com/lakijafexe/1/edit
请记住,shadowRoot 不是 "tag",因此您会在示例中看到 undefined for tagName。
我无法将动态 HTML 直接添加到聚合物元素,而是似乎被迫将其添加到现有的子元素。这是聚合物的限制,还是我缺乏理解?
虽然有另一个 div 肯定很受欢迎,但我真的希望聚合物能帮助我把它放在我的评论镜中。
例子
对于以下元素:
<polymer-element name="my-el1">
<template>
<div id='myid'></div>
</template>
</polymer-element>
此脚本仅在添加到 div (#myid) 而不是直接添加到模板时显示:
<script>
var el = document.createElement('div');
el.innerHTML = 'text';
this.appendChild(el); //shows in DOM, not in browser
this.$.myid.appendChild(el); //works
</script>
JSBIN
完整示例位于 jsbin
this
引用 Polymer 对象而不是实际的 DOM。为了直接在阴影中添加一些东西DOM,你需要使用以下内容:
this.shadowRoot.appendChild(el);
这是您的 JSBin:http://jsbin.com/lakijafexe/1/edit
请记住,shadowRoot 不是 "tag",因此您会在示例中看到 undefined for tagName。