简体   繁体   English

多次向网页插入自定义 HTML 元素的一个实例

[英]Insert to web-page one instance of custom HTML element more than once

As example, I dynamically create instance of some custom HTML element.例如,我动态创建了一些自定义 HTML 元素的实例。 After this, I twice use document.body.appendChild() and this work, but this should no be.在此之后,我两次使用document.body.appendChild()和这项工作,但这不应该。 What I may do for prevent this?我可以做些什么来防止这种情况发生?

I put sample about this situation below in the text.我在下面的文本中放了关于这种情况的示例。 RandomParagraphSizePlaceholder is simple web-component from some book. RandomParagraphSizePlaceholder是某本书中的简单网络组件。 I use it only for illustration purposes.我仅将其用于说明目的。

在此处输入图像描述

https://jsfiddle.net/h6cxjae5/ https://jsfiddle.net/h6cxjae5/

PS I see, that is something wrong with web component, may be. PS 我明白了,这可能是 web 组件有问题。

Only one instance of web component exists in web-page.网页中只有一个web组件实例。 But web component content is duplicated.但是web组件内容重复了。 May be, because it created in connectedCallback .可能是,因为它是在connectedCallback中创建的。 I dont very famimiliar with web component:(.我不太熟悉 web 组件:(。

You get two instances, because your code:你得到两个实例,因为你的代码:

 this.appendChild(document.importNode(placeholder.content, true));

effectively makes a copy (importNode) and then appends another element.有效地制作一个副本(importNode),然后附加另一个元素。

connectedCallback (corretcly running twice) has (in this case) nothing to do with it. connectedCallback (正确地运行了两次)(在这种情况下)与它无关。

https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM