admin管理员组文章数量:1186977
How can I access node that have dynamic id value using Polymer node finding by id?
For example
<template>
<div id="{{ id }}"></div>
</template>
and in js
Polymer("my-element", {
ready: function() {
if (!this.id) {
this.id = 'id' + (new Date()).getTime();
}
console.log(this.$.id); // this part needs to find my div element
}
});
How can I access node that have dynamic id value using Polymer node finding by id?
For example
<template>
<div id="{{ id }}"></div>
</template>
and in js
Polymer("my-element", {
ready: function() {
if (!this.id) {
this.id = 'id' + (new Date()).getTime();
}
console.log(this.$.id); // this part needs to find my div element
}
});
Share
Improve this question
asked Jul 5, 2014 at 17:04
wormhitwormhit
3,82740 silver badges46 bronze badges
4 Answers
Reset to default 20It's true that a JavaScript hash can be accessed using either dot .
or array []
notation. If you have a literal name, you can use dot notation this.$.some_id
. If you have an indirection, like this.id = 'some_id'
, then you can use array notation this.$[this.id]
to find the same value.
The tricky part is that Polymer only populates $
array after first stamping the template, which happens before ready
. If you had an external binding to this.id
, this.$.[this.id]
would work, but since you are setting this.id
in ready
it's too late for the $
convenience.
In this case, you can instead query your shadowRoot directly:
this.shadowRoot.querySelector('#' + this.id)
Pro tip: at some point a subclass may supply a new template, in which case this.shadowRoot
will point to the new shadow-root and not the superclass version. For this reason, it's best to install a named div you can query against, e.g. this.$.id_div.querySelector('#' + this.id')
.
You can use $
like a hash:
id = 'computed_element_id';
this.$[id];
Polymer provides a method to this (source):
For locating dynamically-created nodes in your element's local DOM, use the $$ method:
this.$$(selector)
$$
returns the first node in the local DOM that matches selector.
In your case, this should work:
console.log(this.$$('#' + id));
According to this document in Polymer 2.x
$$
is not supported, so usethis.shadowRoot.querySelector
instead.
console.log(this.shadowRoot.querySelector('#' + id));
If you are using Polymer 1.x then you can use $$
.
本文标签: javascriptPolymer automatic node finding with dynamic id valueStack Overflow
版权声明:本文标题:javascript - Polymer automatic node finding with dynamic id value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738363720a2081213.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论