Polymer 1.x:势必访问dom-if模板中的DOM节点

时间:2016-09-09 23:31:05

标签: polymer polymer-1.0 dom-if

Here is my jsBin

我想通过id dom-if模板中的true DOM节点进行访问。使用我现有的代码,我希望在尝试将这些节点转换为布尔值时看到false,而是获得undefined(即Foo)。

重新创建问题的步骤:

  1. Open this jsBin
  2. 通过展示BarBaz并且不显示id="foo",了解右侧的HTML窗格是否正常工作。
  3. 观察控制台并了解id="bar"节点是否可访问,但id="baz"<!doctype html> <head> <meta charset="utf-8"> <base href="https://polygit.org/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link href="polymer/polymer.html" rel="import"> <link href="iron-form/iron-form.html" rel="import"> </head> <body> <dom-module id="x-element"> <template> <style></style> <div id="foo">Foo</div> <template is="dom-if" if="{{show}}"> <div id="bar">Bar</div> </template> <template is="dom-if" if="{{!show}}"> <div id="baz">Baz</div> </template> </template> <script> (function(){ Polymer({ is: "x-element", properties: { show: { type: Boolean, value: function() { return true; } } }, attached: function() { console.log('foo', !!this.$.foo); console.log('bar', !!this.$.bar); console.log('baz', !!this.$.baz); }, }); })(); </script> </dom-module> <x-element></x-element> </body> 元素不可访问。这是我的问题。
  4. 如何强制访问这些节点?

    http://jsbin.com/kemoravote/1/edit?html,console,output
    self.add

1 个答案:

答案 0 :(得分:0)

$选择器不起作用。您必须使用$$,如下所示:

console.log('baz', !!this.$$('#baz'));

Here is the jsBin

http://jsbin.com/xogediyato/1/edit?html,console,output

<!doctype html>
<head>
  <meta charset="utf-8">
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import">
  <link href="iron-form/iron-form.html" rel="import">
</head>
<body>

  <dom-module id="x-element">

    <template>
      <style></style>
      <div id="foo">Foo</div>
      <template is="dom-if" if="{{show}}">
        <div id="bar">Bar</div>
      </template>
      <template is="dom-if" if="{{!show}}">
        <div id="baz">Baz</div>
      </template>

    </template>

    <script>
      (function(){
        Polymer({
          is: "x-element",
          properties: {
            show: {
              type: Boolean,
              value: function() {
                return true;
              }
            }
          },
          attached: function() {
            console.log('foo', !!this.$.foo);
            console.log('bar', !!this.$.bar);
            console.log('baz', !!this.$.baz);
            console.log('bar', !!this.$$('#bar'));
            console.log('baz', !!this.$$('#baz'));
          },
        });
      })();
    </script>

  </dom-module>

  <x-element></x-element>

</body>