2016-07-25 180 views
11

如何在聚合物自定义元素中使用getElementById?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

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

回答

11

我最好使用

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'; 
    } 

}); 
+0

感谢您的帮助!解决问题的方式就像你在上一个答案中所做的一样(其他人不为我工作)。 1.修正了“in the class name。2. instead of properties I used used'this.hiddenClass'。Thanks again。 –

+0

感谢您的反馈并为错误而感到遗憾,我自己只使用Dart。 –

+0

我相信正确的语法'ready'处理程序是'this。$。hideme'和'this。$$('#hideme')'。 –

0

你的问题其实是,当准备回调被激发你的元素没有连接到文档DOM。对于简单地显示/隐藏元素,您可以使用像这样的隐藏属性:<div hidden$="{{!shouldShow}}">