首页 > 解决方案 > 在脚本 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">

标签: javascriptjqueryhtml

解决方案


我认为一种解决方案是动态创建该脚本元素

<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>

推荐阅读