【问题标题】:Variable in SRCSRC 中的变量
【发布时间】:2020-03-08 06:41:19
【问题描述】:

我在我的 HTML 代码中插入了一个天气小部件,它显示了用户所在城市的天气。我正在尝试使用地理定位脚本来显示 IP 位置的天气,因为小部件固定在一个城市上,但我不知道如何在 SRC url 中显示变量,这是我的代码,你能帮忙吗我来解决我的问题,我真的很感激:

    <script id="imageBox" type="text/javascript" class="w3-bar-item w3-button w3-center" src=""></script>
    <script type="text/javascript">
$.ajax({
  url: "https://get.geojs.io/v1/ip/geo.js",
  jsonpCallback: "geoip",
  dataType: "jsonp",
  success: function(location) {
    $('#country').html(location.country_name);
    $('#countrycode').html(location.country_code);
    $('#state').html(location.state);
    $('#city').html(location.city);
    $('#latitude').html(location.latitude);
    $('#longitude').html(location.longitude);
    $('#ip').html(location.ip);
  var latitudevar = location.latitude;
  var longitudevar = location.longitude;
  document.getElementById('imageBox').src = 'https://darksky.net/widget/default-small/' + latituidevar + ',' + longitudevar + '/uk12/en.js?width=50%&height=70&title=Full Forecast&textColor=000000&bgColor=transparent&transparency=true&skyColor=undefined&fontFamily=Default&customFont=&units=uk';

  }

}); 
    </script>

【问题讨论】:

  • 这看起来不错。你确定 ajax 请求成功了吗?
  • 是的,我尝试使用以纬度和经度为 ID 的 Div。
  • 我明白了,您更改了脚本标签的 src。那是不可能的。这仅适用于imgiframe 等媒体标签。您必须创建一个新的脚本标签。
  • 那么我该如何创建这个“变量”src?

标签: javascript php html src


【解决方案1】:

我明白了,您更改了脚本标签的 src。那是不可能的。这仅适用于imgiframe 等媒体标签。您必须创建一个新的脚本标签。

在您的 AJAX 请求代码的末尾,您可以这样做:

// source attribute
let src = 'https://darksky.net/widget/default-small/' + latituidevar + ',' + longitudevar + '/uk12/en.js?width=50%&height=70&title=Full Forecast&textColor=000000&bgColor=transparent&transparency=true&skyColor=undefined&fontFamily=Default&customFont=&units=uk';

// create a script tag and set the source
let s = document.createElement('script');
s.src = src;

// find the head tag and append the script tag
document.getElementsByTagName('head')[0].appendChild(s);

你可以完全删除

<script id="imageBox" type="text/javascript" class="w3-bar-item w3-button w3-center" src=""></script>

我也无法想象你为什么要为 script 标签赋予一个类属性,因为它永远不会显示在 DOM 中。

【讨论】:

  • 我发现我的页面没有加载脚本,因为我包含一个 document.write 并且是异步的,有帮助吗?
猜你喜欢
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2018-07-01
  • 1970-01-01
  • 2014-04-14
相关资源
最近更新 更多