访问自定义元素的子节点?

2024-02-27

这可能有点令人困惑。我正在尝试从我的自定义元素访问innerHTML 或childNodes。是否可以从Web组件导入文件访问原始DOM结构?在 AttachShadow 之前?

在下面的示例中,我尝试从 jookah-gallery 导入文件访问两个 jookah-images 的 src。

免责声明:当涉及到 Shadow DOM 和 Web 组件时,我完全是个菜鸟,所以如果有任何重大错误,我很想了解原因。谢谢你的帮助!

索引.html

<jookah-gallery>
    //here
    <jookah-image class="gallery-image" src="http://merehead.com/blog/wp-content/uploads/gradient-design.jpeg">
    <jookah-image class="gallery-image" src="https://webgradients.com/public/webgradients_png/035%20Itmeo%20Branding.png">
</jookah-gallery>

jookah-gallery 的导入文件:

(function(owner) {

    class jookahGallery extends HTMLElement {

        constructor() {

            super();

            //this returns false
            if (this.hasChildNodes()) {
                console.log('there are nodes')
            }else{
                console.log('NO nodes')
            }

            //shadow DOM attach
            const shadowRoot = this.attachShadow({mode: 'open'});
            const template = owner.querySelector('#jookah-gallery-template');
            const instance = template.content.cloneNode(true);
            shadowRoot.appendChild(instance);


        }

        // ---------------- object events -------------------------//

        connectedCallback() {
        }

        render(){
        }

        disconnectedCallback(){
        }

        attributeChangedCallback(){
        }

        // ---------------- methods ------------------------//


    }

    customElements.define('jookah-gallery', jookahGallery);

})(document.currentScript.ownerDocument);

根据规范,您不应该在 Web 组件的构造函数中检查、更改、添加子项。

https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance

相反,您需要将孩子们的阅读移至连接的回调中:

class jookahGallery extends HTMLElement {
  constructor() {
    super();
    this._childrenRead = false;

    const shadowRoot = this.attachShadow({mode: 'open'});
    const template = document.createElement('template');
    template.innerHtml = `Place your template here`;
    const instance = template.content.cloneNode(true);
    shadowRoot.appendChild(instance);
  }

  connectedCallback() {
    if (!this._childrenRead) {
      this._childrenRead = true;

      if (this.hasChildNodes()) {
          console.log('there are nodes')
      }else{
          console.log('NO nodes')
      }
    }
  }
}

customElements.define('jookah-gallery', jookahGallery);

您还可以使用<slot> https://developers.google.com/web/fundamentals/web-components/shadowdom#slots嵌入您的孩子。但是有一些CSS问题你需要解决意识到 https://developers.google.com/web/fundamentals/web-components/shadowdom#stylefromoutside使用插槽时。

请记住,shadowDOM 并非在所有浏览器中都受支持,并且不是一个简单的填充。因此,如果您只使用 Chrome 和 Safari,那就去吧。如果您计划支持更广泛的浏览器,那么您可能还不想使用 ShadowDOM。

https://alligator.io/web-components/composition-slots-named-slots/ https://alligator.io/web-components/composing-slots-named-slots/

还可以在这里阅读更多内容:如何在 Web 组件中使用子元素 https://stackoverflow.com/questions/49027807/how-to-use-child-elements-in-web-components

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问自定义元素的子节点? 的相关文章

随机推荐

  • 如何在 iframe 中正确显示 SSRS 站点

    I have been working on a project where I need to load a ssrs site within an iframe The iframe is acutally using the tele
  • android webview 中的 onShowFileChooser() 只能运行一次

    我需要从设备中选取图像并将其上传到服务器 第一次 当我选择图像时 onShowFileChooser 被调用并且一切正常 但是 当我尝试再次单击上传时 onShowFileChooser 永远不会被调用 但它适用于非棒棒糖设备 每当我单击上
  • 无法从 Google Places API 获取特殊营业时间

    特别营业时间在以下位置进行营销 记录谷歌我的商家 see https support google com business answer 6303076 https support google com business answer 6
  • Java时间解析“Jun 26th 2021, 04:30:15 pm NY”

    我有一个看起来像这样的字符串 String str Jun 26th 2021 04 30 15 pm NY 我想将其转换为ZonedDateTime 为此我使用DateTimeFormatterBuilder DateTimeFormat
  • 显式非单参数构造函数

    谁能解释为什么非单参数构造函数标记为显式编译 据我了解 这在这里绝对是无用的关键字 那么为什么它编译时没有错误呢 class X public explicit X int a int b 在 C 03 中 在这种特殊情况下 标记两个参数构
  • wxWidgets:如何捕捉wxListCtrl上的左键单击?

    我想将复选框添加到 wxListCtrl 这工作正常 只是当鼠标单击项目时似乎没有 EVT LIST ITEM CLICK 或 EVT LIST ITEM LEFT CLICK 事件来捕获 以便可以切换图像 有右键单击和中键单击的事件 但没
  • PHP CURL - 如何判断请求的整个文件是否未完全下载

    我使用 CURL 和代理来获取一些 xml 文件 有时当我尝试加载 使用 xml simplexml load string 时 只有部分 XML 文档会通过并失败 我想像 if curl errno ch error curl error
  • jQuery - 即使单击列表也会触发,但不会触发嵌入其中的复选框

    我正在制作一个简单的网络应用程序 在一部分中 我动态创建了一个列表 然后我有一个事件 当单击列表中的任何元素时会触发 document on click list not checkbox function console log list
  • 递归块过早释放

    我写了一个递归块如下these http ddeville me 2011 10 recursive blocks objc 指导方针 NSMutableArray groups NSMutableArray arrayWithArray
  • 从 Dns.GetHostEntry() 获取 IPv4 地址

    我这里有一些代码在 IPv4 机器上运行得很好 但在我们的构建服务器 IPv6 上却失败了 简而言之 IPHostEntry ipHostEntry Dns GetHostEntry string Empty GetHostEntry 的文
  • C++ 返回字符串不断出现垃圾

    为什么这里的返回字符串上有各种垃圾 string getChunk ifstream in char buffer 5 for int x 0 x lt 5 x buffer x in get cout lt lt x lt lt lt l
  • 未找到符号:__PyCodecInfo_GetIncrementalDecoder

    自从从 Homebrew Python 2 7 11 从 2 7 10 开始 更新后 我突然无法从 PyCharm IDE 控制台在 PyPi 上测试注册我的包 运行 作为 外部工具 python B setup py register r
  • 显示 Pandas 数据框的所有行和列[重复]

    这个问题在这里已经有答案了 我正在 Visual Studio 代码中使用 python 3 和 pandas 包 但 print 函数无法正确显示 例如 当我使用 df head 时 它看起来不错 但是 如果我使用 print 语句 我将
  • 在哪里可以找到被新功能弃用的 Android 功能列表?

    Android 开发者网站中是否有某些内容显示了 API 中的某些附加功能已弃用的内容 例如 一个人如何知道 Fragment 不赞成使用什么内容 Update 新的发行说明可以在此处的新 URL 上以更易于阅读的格式获取 https de
  • 从字符串中删除非 utf8 字符

    我在从字符串中删除非 utf8 字符时遇到问题 这些字符无法正确显示 字符是这样的 0x97 0x61 0x6C 0x6F 十六进制表示 去除它们的最佳方法是什么 正则表达式还是其他什么 如果您申请utf8 encode 对于已经是 UTF
  • 带有计算属性名称的 Typescript setState

    我正在使用 Typescript 2 1 我有一个带有 2 个数字集合的状态的 React 组件 我不想重复 addItem 和 removeItem 方法并希望它们是通用的 这是代码 type Collection challenges
  • 如何将 pyinstaller 与 pipeline/pyenv 一起使用

    我正在尝试从我的 python 脚本中发送一个可执行文件 该脚本位于使用 pipelinev 的虚拟环境中 它再次依赖 pyenv 进行 python 版本控制 为此 我想要使用 pyinstaller 我做了什么 pipenv insta
  • 如何使用 Amazon Marketplace Web Service (Amazon MWS) API 更新产品价格

    只是试图找出更新亚马逊市场商店的产品价格有多容易 或者可能有多困难 经过一番搜索后 我找到了有关的文档 亚马逊商城网络服务 亚马逊MWS https developer amazonservices com gp mws docs html
  • TcpClient 开始连接超时

    如何在 C 中为 BeginConnect 异步调用设置自定义超时 它非常有用 当连接到主 机时有可能不侦听给定端口 每个这样的调用在释放线程之前都会浪费大约 15 秒的时间 我有以下代码 正如许多 stackoverflow 答案中所建议
  • 访问自定义元素的子节点?

    这可能有点令人困惑 我正在尝试从我的自定义元素访问innerHTML 或childNodes 是否可以从Web组件导入文件访问原始DOM结构 在 AttachShadow 之前 在下面的示例中 我尝试从 jookah gallery 导入文