访问Polymer中的所有内部元素? [英] Accessing all inner elements in Polymer?
问题描述
我有:
<k-myelement>
<k-anotherelement></k-anotherelement>
</k-myelement>
当我这样定义模板时:
<polymer-element name="k-myelement">
<template>
<content select="k-anotherelement" id="anotherelement"></content>
</template>
</polymere-element>
我可以使用this.$['anotherelement']
但是使用这种方法,我必须预先定义可以使用哪些内部元素.
But with this approach I have to predefine, which inner elements can be used.
我想要的是一种模板技术,它允许我访问所有内部元素.
What I want is a template technique, that allows me to access all the inner elements.
推荐答案
<content>
(表示在此处渲染任何<k-anotherelement>
元素.如果要邀请所有轻型DOM节点加入渲染方,只需使用<content></<content>
.
<content>
(insertion points) are for rendering elements in the light DOM at specific locations in the Shadow DOM. Using <content select="k-anotherelement"></content>
says "render any <k-anotherelement>
elements here. If you want all light DOM nodes to be invited into the rendering party, simply use <content></<content>
.
您的代码段存在其他问题:
The other issues with your snippet:
- 元素的名称需要在
<polymer-element>
上定义,而不是在<template name="k-myelement">
上定义
-
要获取通过
<content>
的节点列表,请使用content.getDistributedNodes()
.您可能还需要考虑是否甚至需要<content>
.轻型DOM子节点可以使用.children
和其他访问器进行访问.来自聚合物文档:
- The name of the element needs to be defined on
<polymer-element>
, not as<template name="k-myelement">
To get the list of nodes that pass through a
<content>
, usecontent.getDistributedNodes()
. You may also want to consider if you even need<content>
. Light DOM children nodes can be access with.children
and the other accessors. From the Polymer docs:
对于
<content>
,您可以遍历content.getDistributedNodes()
以获取在插入点处分布的节点的列表.
For a
<content>
, you can iterate throughcontent.getDistributedNodes()
to get the list of nodes distributed at the insertion point.
在Polymer中,调用此方法的最佳位置是在attached()
回调中,因此可以确保该元素位于DOM树中.
In Polymer, the best place to call this method is in the attached()
callback so you’re guaranteed that the element is in the DOM tree.
还请记住,您可以将light DOM作为元素的普通子级(即this.children
或其他访问器)进行访问.这种方法的区别在于,它是整个潜在分布的节点的整个集合.不是那些实际分发的.
Also remember that you can access the light DOM as the element’s normal children (i.e. this.children
, or other accessors). The difference with this approach is that it’s the entire set of potentially distributed nodes; not those actually distributed.
这篇关于访问Polymer中的所有内部元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!