【问题标题】:Custom properties on Custom Elements自定义元素上的自定义属性
【发布时间】:2021-04-27 05:53:19
【问题描述】:

在自定义元素被解析并添加到 DOM 之后,我是否可以访问我在构造函数时创建的自定义属性,例如:

    const props = []
    return new CustomElement(props)

    // later in code

    class CustomElement {
      ...
      constructor(props) {
         this.customProperty = props
      }
      toString() {
         return this.outerHTML
      }
      ...
    }

    // later in code
    const ce = document.querySelector("custom-element")
    console.log( ce.customProperty ) // []

【问题讨论】:

  • 您需要确保您的自定义元素已正确注册customElements.define('custom-element', CustomElement);
  • 显示代码的目的是关注问题的相关方面。当然我已经定义了元素。 @connexo

标签: javascript custom-element


【解决方案1】:

是的,与常规 DOM 元素没有什么不同。

有了document.createElement("custom-element"),你的财产也在那里。

注意后者只执行了constructor
所以你在connectedCallback 中添加的道具还不会被设置。

对于这些类型的问题,请在 JSFiddle 或 CodePen 或 https://webcomponents.dev 中尝试您自己的代码

【讨论】:

  • 您至少在回答问题之前尝试过吗?这在任何情况下都不起作用。
猜你喜欢
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多