gpt4 book ai didi

javascript - 使用 X-Tag 创建自定义子元素的正确方法

转载 作者:行者123 更新时间:2023-11-30 09:40:24 25 4
gpt4 key购买 nike

所以我知道 x-tag web component library使您能够像这样创建出现在 HTML 中的自定义元素:

<x-my-custom-element>my content</x-my-custom-element>

但是,如果我想创建多个自定义子元素,就像这样:

<x-my-custom-element>
<x-my-custom-element-child>
<x-my-custom-element-grandchild></x-my-custom-element-grandchild>
</x-my-custom-element-child>
</x-my-custom-element>

正确的方法是简单地调用 xtag.register() 三次,如下所示:

xtag.register('x-my-custom-element', {...});
xtag.register('x-my-custom-element-child', {...});
xtag.register('x-my-custom-element-grandchild', {...});

还有,有什么方法可以强制一个子元素始终是另一个元素的子元素吗?换句话说,这会起作用:

<x-my-custom-element-parent>
<x-my-custom-element-child></x-my-custom-element-child>
</x-my-custom-element-parent>

但这不会:

<x-my-custom-element-child>
<x-my-custom-element-parent></x-my-custom-element-parent>
</x-my-custom-element-child>

最佳答案

因为您的自定义元素名称是有效的(包含“破折号”- 字符),您只需要使用 xtag.register() 注册它们如果您需要添加功能、属性、默认内容、影子 DOM 等。具有无法识别但有效名称的元素将只是 HTMLElement对象。具有无法识别和无效名称的元素将是 HTMLUnknownElement对象。

// valid custom element name
document.createElement('foo-bar') instanceof HTMLElement; // true

// invalid custom element name
document.createElement('foobar') instanceof HTMLUnknownElement; // true

您可以阅读 WHATWG Spec for HTMLUnknownElement here .

我不知道有什么方法可以强制元素层次结构。标准 HTML 元素不强制执行此操作。例如,你可以做 <li><ul></ul></li><source><video></source> .如果像这样使用不当,这些元素根本无法发挥作用。

关于javascript - 使用 X-Tag 创建自定义子元素的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394425/

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