如何获取自定义元素的内容 [英] How to Get the Contents of a Custom Element
问题描述
我正在创建自定义元素能够将其内容从markdown转换为HTML.但是,我无法获取自定义元素的内容.
I'm creating a custom element that will be able to convert its contents from markdown to HTML. However, I'm not able to get the contents of my custom elements.
<!doctype html>
<html>
<body>
<template id="mark-down">
<div class="markdown"></div>
</template>
<!-- Converts markdown to HTML -->
<script src="https://cdn.jsdelivr.net/gh/showdownjs/showdown/dist/showdown.js"></script>
<script>
customElements.define('mark-down',
class extends HTMLElement {
constructor() {
super()
let template = document.querySelector('#mark-down').content
this.attachShadow({ mode: 'open' }).appendChild(template.cloneNode(true))
}
connectedCallback() {
console.log(this) // Returns the whole <mark-down> node and its contents
console.log(this.innerHTML) // So why does this return a blank string?
// This should theoretically work --> let markdown = this.innerHTML
let markdown = '## Test'
let converter = new showdown.Converter()
let html = converter.makeHtml(markdown)
this.shadowRoot.innerHTML = html;
}
});
</script>
<main>
<mark-down>
## Our Markdown
These contents should get converted
* One
* Two
* Three
</mark-down>
</main>
</body>
</html>
我的问题在connectedCallback()
中.记录this
时,我得到了整个<mark-down>
节点,其内容在markdown中.但是,它似乎没有有效的属性.使用innerHTML
返回一个空白,该空白应返回降价;其他组合,例如this.querySelector('mark-down')
,返回null
.
My issue is in the connectedCallback()
. When logging this
, I get the whole <mark-down>
node with its contents in markdown. However, it doesn't seem to have valid properties. Using innerHTML
returns a blank, where it should return the markdown; other combinations, like this.querySelector('mark-down')
, return null
.
如何获取自定义元素的内容?
What can I do to get the contents of my custom element?
推荐答案
我已经被 this 咬伤了,我特意问了一个StackOverflow问题,让人们找到
I have been bitten by this so much, I purposely asked a StackOverflow question for people to find
等待connectedCallback中的元素升级:FireFox和Chromium的差异
wait for Element Upgrade in connectedCallback: FireFox and Chromium differences
最简单的解决方法是connectedCallback
<script>
customElements.define('my-element', class extends HTMLElement {
connectedCallback() {
console.log(this.innerHTML);// "A" in FireFox, "" in other Browsers
setTimeout(() => {
// now runs asap
console.log(this.innerHTML); // "A"
});
}
})
</script>
<my-element>A</my-element>
此操作和所有提到的解决方法的作用是将代码执行推迟到完全解析DOM为止.
setTimeout
在DOMContentLoaded
之后运行,但是如果将所有内容包装在DOMContentLoaded
中,则整个元素创建都将延迟进行,同样适用于defer
或将<script>
放置在页面末尾
What this and all mentioned workarounds do is postpone code execution until the DOM is fully parsed.
setTimeout
runs after DOMContentLoaded
, but if you wrap everything in DOMContentLoaded
the whole Element creation runs late, same applies for defer
or placing <script>
at the end of your page
Supersharp解释了为什么更好:
Supersharp explains the why better in:
等待connectedCallback中的元素升级:FireFox和铬的差异
这篇关于如何获取自定义元素的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!