2017-08-02 120 views
2

我試圖學習聚合物2.0,但我堅持從一個不同的陰影Dom元素的問題。這工作在聚合物1,但不再在聚合物2.0。寫這個的正確方法是什麼?它只是告訴我,targetText = Null聚合物2.0 getElementById在不同的ShadowDom

感謝您的幫助!

這是一個MWE: 聚合物WC 1:

<dom-module id="sc-navdrawer"> 
<template> 
<style is="custom-style"> 
p { 
    font-weight: bold; 
} 
.changed { 
    color: red; 
} 
</style> 
<p>Some text in normal p tag</p> 
<div id="test" class="htmltextcontent" inner-h-t-m-l="{{inputText}}"></div> 
</template> 

<script> 
    Polymer({ 
     is: 'sc-navdrawer', 
     properties: { 
      inputText: { 
      type: String, 
      value: "<p>Some innerhtml text in p tags</p>" 
      } 
     } 
    }); 

</script> 
</dom-module> 

聚合物WC 2:

<dom-module id="sc-testpage"> 
<template> 

<button onclick="{{changeColor}}">Click here to change color</button> 
</template> 

<script> 
    Polymer({ 
     is: 'sc-testpage', 
     changeColor: function() { 
      var targetText = document.getElementById("test"); 
      console.log(targetText); 
      targetText.classList.add("changed"); 
     } 
    }); 

</script> 
</dom-module> 
+0

是反正這兩個要素的相互關係?這意味着他們有一個孩子的父母關係? – Niklas

回答

2

那麼我看到的第一件事是你使用document.getElementById("test");,如果你說這個工作,你已經使用了Shady Dom。
聚合物2迫使您使用Shadow Dom,因此該命令應該由Polymer.dom(this.root).querySelector("#test")替代。由於Shadow Dom封裝了您的組件,因此無法使用document對象
訪問其內容,但這不應解決您的問題。此封裝意味着您無法訪問WebComponent的內容,因此您無法從另一個組件訪問id爲xyz的元素。看看這些鏈接,他們會向你解釋shadowDom如何工作的:
1. https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
2. https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM
3. https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/

+0

謝謝。是的,這確實是問題所在。感謝您的鏈接;我會通讀他們。我也注意到,我無法從同一個WC中訪問元素。 – Vims

+0

謝謝。你把我放在正確的軌道上。我仍然必須習慣這個,但我得到它的工作! – Vims

+0

真棒聚合物在一開始就很奇怪,但一旦你完全理解它,它變得非常強大;-) –

0
  1. 而不是使用的getElementById的,你應該使用Automatic node finding這工作,如果你的兩個元素有彼此的父子關係。
  2. 我也相信不是在WC 2中使用onclick按鈕,而應該使用on-tap。這是Polymer文檔中推薦的方法。

  3. 此外,我不明白你爲什麼在你的onclick屬性上使用雙向數據綁定。我可能會錯過一些東西,但是你的代碼應該在正常的函數調用中工作得很好。

    <dom-module id="sc-testpage"> 
        <template> 
        <button on-tap="changeColor">Click here to change color</button> 
        </template> 
    
        <script> 
        Polymer({ 
         is: 'sc-testpage', 
    
         changeColor: function() { 
         var targetText = this.$.sc-navdrawer.$.test; 
         console.log(targetText); 
         targetText.classList.add("changed"); 
         } 
        }); 
    
        </script> 
    </dom-module> 
    
+0

謝謝你的回答。事實上,雙向綁定並不是必要的,也不是單擊,但我做了一個非常快速的MWE來展示問題。我嘗試了你的建議,但那不起作用:不是兩個元素具有相同的父級,也沒有sc-navdrawer是sc-testpage的父級,反之亦然。此外,我認爲在你的代碼中,它不得不說'this。$。scNavdrawer。$。test'。無論如何,它總是將targetText作爲Null返回。我認爲這在Polymer 2中已經發生了變化。 – Vims

+1

實際上,第1點至少是關於孩子父母事物的部分是錯誤的。這隻對Polymer 1和陰暗的dom有效。 –

0

嘗試使用紙張輸入和設置它的值:

<paper-input id="test" label="input" value="{{inputText}}"></paper-input>

然後你就可以訪問變量是這樣的:

var targetText = this.$.inputText;

( THI s應該與除了紙張輸入以外的其他元素一起工作)