代码之家  ›  专栏  ›  技术社区  ›  Vims

不同阴影中的聚合物2.0 getElementById

  •  4
  • Vims  · 技术社区  · 7 年前

    targetText = Null

    谢谢你的帮助!

    聚合物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>
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Pascal L.    7 年前

    我看到的第一件事是你使用 document.getElementById("test"); 如果你说这奏效了,你就用了Shady Dom。
    Polymer.dom(this.root).querySelector("#test") 。由于阴影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/

        2
  •  0
  •   tal weissler    7 年前

    尝试使用纸张输入并设置其值:

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

    var targetText = this.$.inputText;

    (这应该适用于除纸张输入之外的其他元素)

        3
  •  0
  •   Niklas    7 年前
    1. 您应该使用getElementById,而不是使用getElementById Automatic node finding 如果您的两个元素彼此具有子-父关系,则此操作有效。
    2. 我还认为,与其在WC 2中使用onclick按钮,不如使用on-tap。这是聚合物文件中推荐的方法。

    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>