问题 Polymer元素中的getElementById


如何在Polymer自定义元素中使用getElementById?

这是我的元素:

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

<dom-module id="bb-calendar">

  <template>

    <style is="custom-style" include="shared-styles"></style>

    <div class="card">
            <paper-toolbar>
                <div title>Calendar</div>
            </paper-toolbar>
            <div id="hideme">
                <div>this should be hidden</div>
            </div>
    </div>

  </template>

  <script>

    Polymer({

      is: 'bb-calendar',

      ready: function() {
        document.getElementById("hideme").style.display = 'none';
      }

    });

  </script>

</dom-module>

当我运行代码时,我收到此错误消息: Uncaught TypeError: Cannot read property 'style' of null

显然我做错了但我不知道是什么。


1731
2017-07-25 08:21


起源



答案:


我用了

ready: function() {
  this.$.hideme.style.display = 'none';
}

当元素在里面时 <template dom-if...> 要么 <template dom-repeat...>

ready: function() {
  this.$$('#hideme').style.display = 'none';
}   

最后,我将使用类绑定并将类绑定到元素并更新属性以反映该更改并使用CSS来设置 style.display

<template>
  <style>
    .hidden { display:none; }    
  </style>
   ...
  <div class$="{{hiddenClass}}">
    <div>this should be hidden</div>
  </div>
Polymer({

  is: 'bb-calendar',

  properties: {
      hiddenClass: String,
  },

  ready: function() {
    this.hiddenClass = 'hidden';
  }

});

11
2017-07-25 08:24



谢谢你的帮助!用你在上一个答案中所做的事情解决了问题(其他人没有为我工作)。 1.修复了“在类名.2。而不是我使用的属性'this.hiddenClass'。再次感谢。 - Zvi Karp
感谢您的反馈并抱歉。我自己只使用Dart。 - Günter Zöchbauer
我相信正确的语法 ready 处理程序是 this.$.hideme,和 this.$$('#hideme')。 - Dan Dascalescu
你是对的,我错过了 this.。谢谢敌人的暗示。 - Günter Zöchbauer


答案:


我用了

ready: function() {
  this.$.hideme.style.display = 'none';
}

当元素在里面时 <template dom-if...> 要么 <template dom-repeat...>

ready: function() {
  this.$$('#hideme').style.display = 'none';
}   

最后,我将使用类绑定并将类绑定到元素并更新属性以反映该更改并使用CSS来设置 style.display

<template>
  <style>
    .hidden { display:none; }    
  </style>
   ...
  <div class$="{{hiddenClass}}">
    <div>this should be hidden</div>
  </div>
Polymer({

  is: 'bb-calendar',

  properties: {
      hiddenClass: String,
  },

  ready: function() {
    this.hiddenClass = 'hidden';
  }

});

11
2017-07-25 08:24



谢谢你的帮助!用你在上一个答案中所做的事情解决了问题(其他人没有为我工作)。 1.修复了“在类名.2。而不是我使用的属性'this.hiddenClass'。再次感谢。 - Zvi Karp
感谢您的反馈并抱歉。我自己只使用Dart。 - Günter Zöchbauer
我相信正确的语法 ready 处理程序是 this.$.hideme,和 this.$$('#hideme')。 - Dan Dascalescu
你是对的,我错过了 this.。谢谢敌人的暗示。 - Günter Zöchbauer


您的问题实际上是在触发就绪回调时您的元素未附加到文档DOM。要简单地显示/隐藏元素,您可以使用隐藏属性,如下所示: <div hidden$="{{!shouldShow}}">


0
2017-07-26 11:29