gpt4 book ai didi

custom-element - 'createElement'上执行 'Document'失败 : The result must not have children

转载 作者:行者123 更新时间:2023-12-03 14:56:16 24 4
gpt4 key购买 nike

我已经通过 polyfill 使用自定义元素 v1 一段时间了。 . Chrome 54(具有 native v1 实现的第一个版本)在初始化我的元素时开始抛出错误:

DOMException: Failed to execute 'createElement' on 'Document': The result must not have children



违规行很简单:
let el = document.createElement('my-custom-element');

最佳答案

Chrome 的 native 实现似乎强制执行 polyfill 没有的规范要求。根据规范的“Requirements for custom element constructors”部分:

The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods.


我试图创建的元素在其构造函数中为其自身添加了子元素。
解决方案是遵循规范的建议:

In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice.


也就是说,在连接的回调中添加子元素并使用标志来确保元素仅在第一次连接时初始化。

关于custom-element - 'createElement'上执行 'Document'失败 : The result must not have children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40181683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com