2016-07-25 179 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}}">