javascript - 在脚本 src 中使用本地存储值
问题描述
如何将我的本地存储值包含在脚本标签的 SRC 值中?
我有这个:
<script id="gmap" async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=">
而我get
的本地价值:
var gkey = localStorage.getItem('LSGMD-GoogleMapsAPIKey');
本地值已设置,当通过警报显示它时,它会正确显示。但是现在我如何在脚本中使用这个本地值。它应该变成:
<script id="gmap" async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=LOCALVALUE">
编辑一:这是我尝试过的,但是虽然它确实改变了 SRC,但它不会显示地图。
<script>
(function ($) {
$(document).ready(function() {
var gkey = localStorage.getItem('LSGMD-GoogleMapsAPIKey');
var glink = "https://maps.googleapis.com/maps/api/js?callback=initMap&key=";
var gscript = glink + gkey;
$("#gmap").attr("src",gscript);
});
})(jQuery);
</script>
我怎样才能在这部分添加一个 var &key=VARHERE">
?
解决方案
我认为一种解决方案是动态创建该脚本元素
<script>
var script = document.createElement('script');
script.onload = function () {
var ipServer = location.host;
};
var gkey = localStorage.getItem('LSGMD-GoogleMapsAPIKey');
script.setAttribute( 'src', 'https://maps.googleapis.com/maps/api/js?callback=initMap&key=' + gkey);
document.head.appendChild(script);
</script>
推荐阅读
- javascript - 决定引导粘性导航栏应该向下多远
- numpy - 如何索引 3d 数组
- javascript - 如何使用 Handlebars.js 在nest.js 中设置默认布局?
- android - 为 Flutter/React-Native/Android-Native 应用程序生成 SHA-1
- watermark - PHPWord生成的带有0边距的docx水印图像从文档的左边缘和上边缘移动了一些空间
- python - 如何使用 pipenv 冻结需求?
- excel - Excel 2013 日期时差
- javascript - 在chartjs栏中合并两个具有不同键的对象
- html - 用于自动化网站的 Excel vba
- javascript - 返回不包括特定范围的随机数 - javascript