gpt4 book ai didi

javascript - 延迟 "manual"将元素升级为定制的内置 Web 组件

转载 作者:可可西里 更新时间:2023-11-01 13:42:55 26 4
gpt4 key购买 nike

我有一个动态创建 div 的 jQuery 插件(我不想修改)。除此之外,我还有一个 Web 组件 scrollable-div,它是从 HTMLDivElement 扩展而来的自定义内置组件。由于我无法控制 jQuery 插件如何创建 div,因此我需要在创建后以及将其添加到 DOM 后对其进行升级。

class myDiv extends HTMLDivElement {
constructor(...args) {
const self = super(...args);
self.addEventListener('click', (e) => {
e.target.textContent = 'clicked'
})
return self;
}
}

customElements.define('my-div', myDiv, { extends: 'div' });

document.addEventListener('DOMContentLoaded', () => {
// this is where I'm trying to turn the div#upgradeMe into a my-div
upgradeMe.setAttribute('is', 'my-div');
});
<div id="upgradeMe">Click me</div>

简单地添加 is="my-div" 属性显然不能解决问题,div 只是保持常规 HTMLDivElement。如何以编程方式将 DOM 中已有的 native 元素升级为自定义的内置 Web 组件?

最佳答案

这是不可能的,因为该元素已经创建为标准 <div>元素,并且由于缺少 is 而在解析为可升级(可扩展)时未被识别属性。

如果自定义元素已经定义,唯一可能的解决方法是用克隆替换现有元素(如@barbsan 的评论中所建议)。

捷径:

  1. 创建一个 <template>元素
  2. 复制div的outerHTML进入其innerHTML属性(property)
  3. 用模板的 content 替换原始元素与 replaceChild()

class myDiv extends HTMLDivElement {
constructor(...args) {
const self = super(...args);
self.addEventListener('click', (e) => {
e.target.textContent = 'clicked'
})
return self;
}
}

customElements.define('my-div', myDiv, { extends: 'div' });

document.addEventListener('DOMContentLoaded', () => {
// this is where I'm trying to turn the div#upgradeMe into a my-div
upgradeMe.setAttribute('is', 'my-div');
var t = document.createElement( 'template' )
t.innerHTML = upgradeMe.outerHTML
upgradeMe.parentElement.replaceChild( t.content, upgradeMe )
});
<div id="upgradeMe">Click me</div>

精度

解析元素时,is 值 会受到影响according to the DOM spec :

Elements have an associated namespace, namespace prefix, local name, custom element state, custom element definition, is value. When an element is created, all of these values are initialized.

仅具有有效 is 的元素属性被标识为可自定义:

An element’s custom element state is one of "undefined", "failed", "uncustomized", or "custom". An element whose custom element state is "uncustomized" or "custom" is said to be defined. An element whose custom element state is "custom" is said to be custom.

因此如果元素没有is解析时的属性,它将不可定制。这就是为什么你不能添加 is之后的属性。

也在HTML specs :

After a custom element is created, changing the value of the is attribute does not change the element's behavior, as it is saved on the element as its is value.

is属性仅在元素创建时(在解析时)用于初始化 is 值,如果在元素已创建时更改则无效。从这个意义上说,是值是只读的。

关于javascript - 延迟 "manual"将元素升级为定制的内置 Web 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51495468/

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