[英]How am I meant to loop through a set of DOM elements within a Polymer 1.0 Element?
I'm trying to loop through a set of static paper-checkbox elements, but my code is failing with: 我试图遍历一组静态的纸张复选框元素,但是我的代码失败:
"Uncaught TypeError: this.querySelectorAll(...).forEach is not a function" “未捕获的TypeError:this.querySelectorAll(...)。forEach不是函数”
The relevant line of code is: 相关的代码行是:
this.querySelectorAll('paper-checkbox').forEach(function(cb) {
I'm sure it's me being dumb - but what am I doing incorrectly in either selecting and/or iterating through the selected (static) checkboxes? 我确定这是我的愚蠢-但是在选择和/或遍历选中的(静态)复选框时,我在做什么错误?
I'm effectively looking for the Polymer 1.0 alternative to JQuery's .each() function. 我正在有效地寻找JQuery的.each()函数的Polymer 1.0替代方案。
Many thanks! 非常感谢!
The problem is this.querySelectorAll('paper-checkbox')
returns a NodeList, not an Array. 问题是this.querySelectorAll('paper-checkbox')
返回一个NodeList,而不是一个Array。 They looks similar but they are different. 它们看起来相似,但有所不同。 NodeList doesn't have the method foreach
on its prototype. NodeList在其原型上没有foreach
方法。
An easy solution is to convert your Nodelist to Array like this: Array.prototype.slice.call(document.querySelectorAll('paper-checkbox'))
一个简单的解决方案是将您的Nodelist转换为Array,如下所示: Array.prototype.slice.call(document.querySelectorAll('paper-checkbox'))
I suggest you to read this article in MDN on this topic. 我建议您阅读MDN中有关此主题的文章 。
This is because 这是因为
this.querySelector('paper-checkbox')
is null. 一片空白。
I think you need to go into the shadow root to get the elements eg 我认为您需要进入影子根目录以获取元素,例如
this.shadowRoot.querySelectorAll('paper-checkbox')
added: 添加:
this.shadowRoot.querySelectorAll('paper-checkbox').array().forEach(function(cb) {
Answer: You need to use dom-repeat
. 答:您需要使用dom-repeat
。
"The dom-repeat element is a custom HTMLTemplateElement type extension that automatically stamps and binds one instance of template content to each object in a user-provided array." “ dom-repeat元素是一个自定义HTMLTemplateElement类型扩展,可以自动标记一个模板内容实例并将其绑定到用户提供的数组中的每个对象。”
<dom-module id="employee-list"> <template> <div> Employee list: </div> <template is="dom-repeat" items="{{employees}}"> <div>First name: <span>{{item.first}}</span></div> <div>Last name: <span>{{item.last}}</span></div> </template> </template> <script> Polymer({ is: 'employee-list', ready: function() { this.employees = [{ first: 'Bob', last: 'Smith' }, { first: 'Sally', last: 'Johnson' }, ...]; } }); </script> </dom-module>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.