2015-05-09 57 views
2

我有按鈕:如何使用Polymer添加動態擴展元素?

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

<polymer-element name="count-button" extends="button" on-click="increment"> 
    <template> 
    <content>Increment: </content> 
    </template> 

    <script> 
    Polymer({ 
     counter: 0, 
     increment: function(e, detail, sender) { 
      this.counter++; 
      alert(this.counter); 
     } 
    }) 
    </script> 
</polymer-element> 

我成功地用它在HTML方式:

<button is="count-button"></button> 

如何在JS添加這樣的按鈕?我的版本不正確(準備功能):

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

<polymer-element name='my-input'> 
    <template> 
     my input 
     <style> 
     </style> 
    </template> 
    <script> 
     Polymer('my-input', { 
      publish: { 
      }, 
      ready: function() { 
       var node = document.createElement("button"); 
       node.setAttribute('is', 'count-button'); 
       this.shadowRoot.appendChild(node); 
      } 
     }); 
    </script> 
</polymer-element> 

回答

1

我發現我自己的解決方案,這是因爲這兩條線一樣簡單:

var node = document.createElement("button", 'count-button'); 
this.shadowRoot.appendChild(node); 

所以,完整的答案就在這裏:

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

<polymer-element name='my-input'> 
    <template> 
     my input 
     <style> 
     </style> 
    </template> 
    <script> 
     Polymer('my-input', { 
      publish: { 
      }, 
      ready: function() { 
       # only these 2 lines 
       var node = document.createElement("button", 'count-button'); 
       this.shadowRoot.appendChild(node); 
      } 
     }); 
    </script> 
</polymer-element>