我打算如何在一个聚合物1.0元素内循环一组DOM元素



我试图通过一组静态纸-复选框元素循环,但我的代码失败了:

"Uncaught TypeError: this.querySelectorAll(…). "forEach不是一个函数"

相关的代码行是:

this.querySelectorAll('paper-checkbox').forEach(function(cb) {

我敢肯定这是我的愚蠢-但我在选择和/或迭代选定的(静态)复选框做错了什么?

我正在有效地寻找替代JQuery的。each()函数的Polymer 1.0。

多谢!

感谢您的回复。我刚刚找到了解决办法。

代替:

this.querySelectorAll()

我应该用:

Polymer.dom(this).querySelectorAll()

现在工作完美!

再次感谢。

问题是this.querySelectorAll('paper-checkbox')返回NodeList,而不是Array。他们看起来很相似,但又不同。NodeList在其原型上没有foreach方法。

一个简单的解决方案是将你的Nodelist转换为数组,像这样:Array.prototype.slice.call(document.querySelectorAll('paper-checkbox'))

我建议你阅读MDN上关于这个主题的文章。

这是因为

this.querySelector('paper-checkbox') 

是null。

我认为你需要进入阴影根目录来获取元素,例如

 this.shadowRoot.querySelectorAll('paper-checkbox')

补充道:

this.shadowRoot.querySelectorAll('paper-checkbox').array().forEach(function(cb) {

答案:您需要使用dom-repeat


根据这里的API文档:

" 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>

最新更新