如何在脚本 type="module"中获取 ownerDocument?
<template>
text
</template>
<script type="module">
let owner = document.currentScript.ownerDocument // is null
// But i need get <template>
let tpl = owner.querySelector('template')
</script>
最佳答案
规范明确指出,当使用 <script type="module">
时document.currentScript
属性设置为 null
在执行期间。 See spec under "execute a script block" .
当然,如果使用 src
就很明显了属性。源无法知道它将被脚本标记而不是导入语句(或两者)调用。内联模块时总是有一个脚本标记,但我猜他们想让体验保持一致。
如果你的文件实际上是window.document
这仍然可以作为一个全局性的。否则,如果您仍希望将脚本作为模块加载,则有两种选择:
不是最漂亮的;在模块上方创建一个全局并存储模板。
<script type="text/javascript"> window.myTemplates = ((ns) => { const owner = window.document.currentScript.ownerDocument; ns.fancyButton = owner.querySelector("template"); return ns; })(window.myTemplates || {}); </script> <script type="module"> const tpl = window.myTemplates.fancyButton; // ... </script>
不要将模板编写为 HTML 模板,而应编写为 ES/JS 模板。您的编辑器可能不支持突出显示文字 HTML,标签的 linting 是一个问题。
<script type="module"> const tpl = window.document.createElement("template"); tpl.innerHTML = ` <strong>example</strong> <span style="background-color: rgba(127,127,127,0.6);">text</span> `; // ... </script>
关于html - 如何获取 <script type ="module"> 中的 document.currentScript.ownerDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228821/