聚合物:在自定义元素中使用querySelector代替"this.$". [英] Polymer: Using querySelector in Custom Element instead of "this.$."

查看:161
本文介绍了聚合物:在自定义元素中使用querySelector代替"this.$".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:刚刚找到此链接,以某种方式对其进行了解释. 使用querySelector在A中查找嵌套元素聚合物模板返回null

Just found this link, that explains it somehow. Using querySelector to find nested elements inside a Polymer template returns null

尽管如此,我还是很乐意回答有关此特定代码的问题.

Nonetheless I'd appreciate an answer to my question on this specific code.

/编辑

我认为这是一个非常简单直接的问题:

I think a rather straight forward and minimalistic problem:

我在聚合物中有一个自定义元素:

I've got a custom element in polymer:

 <polymer-element name="my-test">
    <template>
        <div id="content">
            <h3 id="test">My Test</h3>
            <p id="paragraph">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi dolore consectetur, mollitia eos molestias totam ea nobis voluptatibus sed placeat, sapiente, omnis repellat dolores! Nihil nostrum blanditiis quasi beatae laborum quisquam ipsum!</p>
            <button id="button">Clicke Me!</button>
        </div>

    </template>
    <script>
    Polymer('my-test', {
        ready: function() {
            var button = this.$.button;
            button.addEventListener("click", function() {
                alert("alert");
            });
        }
    });
    </script>
</polymer-element>

问题是,我宁愿使用

 var button = document.querySelector(#button);

代替

 var button = this.$.button;

因为它看起来更加直观和声明.但是每当我这样做时,我都会收到一条错误消息:

Because it seems more intuitive and declarative. But whenever I do this I get an error that says:

 "Uncaught TypeError: Cannot read property 'addEventListener' of null " in Chrome and

 Firefox instead says: "TypeError: button is null"

因此,感谢您提供任何帮助! :)

So any help is appreciated! :)

推荐答案

您的按钮位于Polymer元素内,并且由于Polymer元素的内容位于其影子DOM中,因此无法通过这种方式找到该元素.如果您的<my-test>元素不在另一个元素的影子DOM中,则可以使用this.shadowRoot.querySelector('#button');document.querySelector('* /deep/ #button');document.querySelector('my-test::shadow #button');. /deep/穿过所有阴影DOM边界::shadow仅穿过一个.

Your button is inside your Polymer element and because Polymer elements have their content inside their shadow DOM the element can't be found this way. You can either use this.shadowRoot.querySelector('#button'); or document.querySelector('* /deep/ #button'); or document.querySelector('my-test::shadow #button'); if your <my-test> element is not within the shadow DOM of another element. /deep/ pierces through all shadow DOM boundaries ::shadow just through one.

这篇关于聚合物:在自定义元素中使用querySelector代替"this.$".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆