我有以下内容:

<script type="module">

// some code here to get the <script>'s DOM reference

</script>

有可能吗?

可能有任何这样的 playbook .我想在脚本后面插入HTML,但没有显式引用.

推荐答案

您可以使用classic 的<script>来定义一些全局变量,然后依赖<script type="module">defer x default这一事实,这意味着它们将在所有文档完全解析后、但在DOMContentLoaded触发之前按顺序执行.

此代码只是为了让您大致了解如何在不通过一些data-属性为脚本标签提供显式标识符的情况下实现这一目标,然后您可以在这些属性上运行document.querySelector.

Example repo on GitHub.

NOTE:您应该只复制/粘贴片段中的内容,并在Web服务器上运行即可查看其工作,或者see it on GitHub pages.我认为片段环境是not fully supportive of ES modules.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <script>
            var counted = 1
            var script = null
        </script>
        <p>content before first module script</p>
        <script type="module">
            script = document.scripts[counted++]
            script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
        </script>
        <p>content after first module script</p>
        <script type="module">
            script = document.scripts[counted++]
            script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
        </script>
        <p>content after second module script</p>
        <script type="module">
            script = document.scripts[counted++]
            script.insertAdjacentHTML('afterend', `<p>inserted after ${counted - 1} module script</p>`)
        </script>
        <p>content after third module script</p>
    </body>
</html>

Javascript相关问答推荐

如何在不使用类型化数组的情况下将32位浮点数按位转换为整值?

为什么有些库公开了执行相同任务的方法,但每个方法都处于同步/同步上下文中?

如何使用CSS和JavaScript创建粘性、凝聚力的形状到形状(容器)变形?

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

如何在JavaScript中在文本内容中添加新行

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

如何才能拥有在jQuery终端中执行命令的链接?

GrapeJS -如何保存和加载自定义页面

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

保持物品顺序的可变大小物品分配到平衡组的算法

如何在.NET Core中将chtml文件链接到Java脚本文件?

如何使用JS创建一个明暗功能按钮?

当我在Reaction中创建一个输入列表时,我的输入行为异常

无法读取未定义的属性(正在读取合并)-react RTK

P5JS-绘制不重叠的圆

MongoDB通过数字或字符串过滤列表

使用静态函数保存 node 前的钩子

不允许在对象文本中注释掉的属性