[英]Polymer: How to access elements within the 'content' tag
I have made a custom element, a list with a built-in filter: 我创建了一个自定义元素,一个带有内置过滤器的列表:
Template for 'filter-list': 'filter-list'的模板:
<template>
<content select="item"></content>
</template>
... ...
<filter-list filter='AAA'>
<item class="AAA">1</item>
<item class="AAA">2</item>
<item class="BBB">3</item>
<item class="BBB">4</item>
<item class="CCC">5</item>
<item class="CCC">6</item>
</filter-list>
The idea is that the list will show/hide items that match the class in filter. 我们的想法是列表将显示/隐藏与过滤器中的类匹配的项目。 To this end, I wrote the following callback:
为此,我写了以下回调:
Polymer('filter-list', {
filter: '',
ready: function() {
},
filterChanged: function() {
if(this.filter) {
items = this.$.items.querySelectorAll("."+this.filter);
console.log("Showing "+items.length+" items.");
}
},
});
But I can't get through to the item nodes. 但我无法进入项目节点。
items.length
is always 0. How can I get to the item
-elements of the light DOM within the custom element API? items.length
始终为0.如何在自定义元素API中获取light DOM的item
元素?
You can access the nodes that are inserted with the <content>
tag through the getDistributedNodes()
function. 您可以通过
getDistributedNodes()
函数访问使用<content>
标记插入的节点。
Here is a small complete example for your scenario: 以下是您的方案的一个小完整示例:
<polymer-element name="filter-list" attributes="filter">
<template>
<content id="items" select="item"></content>
</template>
<script>
Polymer('filter-list', {
ready: function() {
this.filter = '';
},
filterChanged: function() {
var items = this.$.items.getDistributedNodes();
for (var i = 0; i < items.length; ++i) {
items[i].style.display = items[i].className == this.filter ? 'block' : 'none';
}
}
});
</script>
</polymer-element>
<polymer-element name="my-app" noscript>
<template>
<input value="{{filter}}">
<filter-list filter="{{filter}}">
<item class="AAA">1</item>
<item class="AAA">2</item>
<item class="BBB">3</item>
<item class="BBB">4</item>
<item class="CCC">5</item>
<item class="CCC">6</item>
</filter-list>
</template>
</polymer-element>
<my-app></my-app>
One can enter the filter string in the input field. 可以在输入字段中输入过滤字符串。 The filter is initially empty, so no items are displayed after a page load.
过滤器最初为空,因此页面加载后不会显示任何项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.