在dom-if模板中聚合物1.0选择元素

时间:2016-04-05 16:49:03

标签: polymer-1.0

我遇到了聚合物1.0的一个常见问题:访问dom-if模板中的节点,但是在我的情况下,所提出的解决方案似乎都不起作用(?!)..

这是一个简单的例子:

<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="my-test">
  <template>
    <div>
      <template is="dom-if" if="{{show}}" id="tplId">
        <p id="message">hello</p>
      </template>
    </div>
    <a on-tap="tapEvent">click me!</a>
  </template>

  <script>
    (function() {
      'use strict';
      Polymer({
        is: 'my-test',
        show: false,
        ready: function() {
        },
        tapEvent: function() {
          // show the template
          this.show = true;

          // How may I access #message since the template is inhert ?

          // this finds the template by id
          console.log(Polymer.dom(tplId));

          // this won't find the #message element inside it
          console.log(Polymer.dom(tplId).querySelector('#message'))

          // this neither
          console.log(Polymer.dom(this.root).querySelector('#message'))

          // this neither
          console.log(Polymer.dom(this).querySelector('#message'))

          // this neither .. Should I even be using this.shadowRoot in 1.0?
          console.log(Polymer.dom(this.shadowRoot).querySelector('#message'))

          // this neither
          console.log(this.$$('#message'))

          // this cannot work because #message is not a statically created DOM element
          console.log(this.$.message)

        }
      });
    })();
  </script>
</dom-module>

我是Polymer的新手,我觉得解决方案可能就在我的鼻子底下......?

1 个答案:

答案 0 :(得分:3)

如果这个

     // this neither
      console.log(this.$$('#message'))

不起作用然后您可能会尝试查询元素,但它不存在。当showfalse时,<p id="message">元素根本不存在。如果您需要,请绑定到hidden,而不是使用dom-if

<p id="message" hidden$="{{show}}">hello</p>

然后

console.log(this.$.message);

也可以。

相关问题