首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用<script>访问html文件中内联JavaScript标记中的变量

使用<script>访问html文件中内联JavaScript标记中的变量
EN

Stack Overflow用户
提问于 2021-11-30 23:06:26
回答 1查看 446关注 0票数 0
代码语言:javascript
复制
<script async src="https://www.googletagmanager.com/gtag/js?id=<key here>"></script>
<script>
    const container = document.getElementById('app');
    const key = container.getAttribute('secret-key');
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', key);
</script>

我正在尝试访问我需要在<script>标签中添加Google的密钥。我能够在第二个代码块中使用

代码语言:javascript
复制
const container = document.getElementById('app');
const key = container.getAttribute('secret-key');

我想对第一个<script>子句使用相同的键,但我不确定是否可以对内联<script>执行相同的操作?我想使用相同的const key来替换<key here>

我怎样才能做到这一点?

编辑

代码语言:javascript
复制
<script>
    function appendGAScriptTag() {
        const configKeys = JSON.parse(container.getAttribute('data-bootstrap')).common.conf;
        const gaKey = configKeys['GOOGLE_ANALYTICS_KEY'];
        let gaScriptTag = document.createElement('script');
        gaScriptTag.type = 'text/javascript';
        gaScriptTag.async = true;
        gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${gaKey}`;
        document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
    }
    appendGAScriptTag(); // <--- calling it here
</script>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-30 23:40:36

您可以使用.动态创建<script>标记。再来点JavaScript!

代码语言:javascript
复制
function appendGAScriptTag() {
  var gaScriptTag = document.createElement('script');
  gaScriptTag.type = 'text/javascript';
  gaScriptTag.async = true;
  gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${document.getElementById('app').getAttribute('secret-key')}`;
  document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
}

当您想将生成的元素注入DOM时,请在预先存在的JavaScript代码中调用JavaScript。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70177207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档