我正在使用 Polymer 1.0 并正在构建一个小型 Accordion 示例。我可以很好地绑定(bind) Accordion 文本的数据,我只想在单击它时更改 Accordion 的图标。
下面是我的代码
<dom-module id="ab-accordion">
<template>
<iron-ajax
auto
handle-as="json"
on-response="handleResponse"
debounce-duration="300"
id="ajaxreq"></iron-ajax>
<template is="dom-repeat" id="accordion" items="{{items}}" as="item">
<div class="accordion" on-click="toggleParentAcc">
<div id="accordion_header" class="accordion__header is-collapsed">
<i class="icon icon--chevron-down"></i>
<span>{{item.name}}</span>
</div>
<div id="standard_accordion_body" class="accordion__body can-collapse">
<div class="accordion__content">
<content id="content"></content>
</div>
</div>
</div>
</template>
</template>
<script>
Polymer({
is: "ab-accordion",
//Properties for the Element
properties: {
accordian: Object,
childaccordions: Object,
// Param passed in from the element - Set if the accordion is open by default.
open: String,
data: String,
reqUrl: {
type: String,
value: "https://example.com/service.aspx"
},
},
ready: function () {
this.items = [];
},
attached: function () {
// Run once the element is attached to the DOM.
},
toggleParentAcc: function (event) { // Toggle the classes of the accordions
//This is where I want to toggle the class
this.$.accordion_header.classList.toggle('is-collapsed');
if (typeof event !== 'undefined') {
event.stopPropagation(); // Stop the click from going up to the parent.
}
},
handleResponse: function (e) {
this.items = e.detail.response.sports;
}
});
</script>
</dom-module>
基本上在 toggleParentAcc
函数中,我想切换 ID 为 accordion_header
的 div 类。但我只是得到 undefined 或 null。
我试过以下两行:
this.$.accordion_header // #1
this.$$('#accordion_header') // #2
我如何访问 dom-repeat 中的那个元素?
更新:我什至无法访问附加函数内 when 内的元素。
attached: function(){
this.$.accordion_header // This is null?!
this.$$('#accordion_header'); // this is also null!
}
最佳答案
https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#node-finding
Note: Nodes created dynamically using data binding (including those in dom-repeat and dom-if templates) are not added to the this.$ hash. The hash includes only statically created local DOM nodes (that is, the nodes defined in the element’s outermost template).
我认为如果您改用 Polymer.dom(this.root)
会更好。另外,我建议您不要在 dom-repeat
中使用静态 ID,因为它们本来就是唯一的。请改用类。
关于javascript - Polymer 1.0 无法访问嵌套 <template> 元素中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31720193/