[英]How to Use JavaScript Variable in HTML src tag
I have a src tag in my HTML which includes a private API key.我的 HTML 中有一个 src 标签,其中包括一个私有 API 密钥。 I didn't want to use the key in the HTML so I made a config.js file so I could reference it from there instead.
我不想使用 HTML 中的密钥,所以我制作了一个 config.js 文件,以便可以从那里引用它。
<script src="main.js"></script>
<script src="config.js"></script>
var token = '12345'
Later, I have to reference in key in the URL and I tried doing this:后来,我必须在 URL 中引用密钥,然后我尝试这样做:
<script async defer
src=`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`>
</script>
The URL is underlined red, but shows no error message. URL 带有红色下划线,但没有显示错误消息。 I was wondering how I would go about doing this.
我想知道我将如何 go 这样做。 Thanks!
谢谢!
Make an html element in javascript and append it to the head Index.html:在 javascript 和 append 中创建一个 html 元素到头部 Index.ZFC35FDC70D5FC69D2539883A8EZCA8227:
<script defer src="scriptTagConfig.js"></script>
scriptTagConfig.js: scriptTagConfig.js:
//Create element
const apiScriptTag = document.createElement("script")
//Set src attribute
apiScriptTag.setAttribute("src",`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`)
//Append to DOM
document.head.appendChild(apiScriptTag)
Construct the <script>
tag dynamically in JavaScript once you have the token.获得令牌后,在 JavaScript 中动态构造
<script>
标记。
const script = document.body.appendChild(document.createElement('script'));
script.src = `https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.