在Javascript中将变量插入另一个字符串变量中

时间:2016-11-03 19:34:52

标签: javascript

我试图将变量latlong放在字符串网址中,但它不起作用。这是我的代码:

$(document).ready(function() {
  var long;
  var lat;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = position.coords.latitude;
      long = position.coords.longitude;

      var api = "http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=c873adc18574701f4fb0abe01d927819";
      $.getJSON(api, function(data) {
        alert(data.name);
      });
    });
  }
});

2 个答案:

答案 0 :(得分:2)

您需要使用相同类型的引号来关闭并重新打开字符串。

class Child extends Parent {
    constructor(...args: [any, any, any, any, any]) {
        super(...args);
    }
}

答案 1 :(得分:0)

或者,如果您正在开发的浏览器支持它,您可以使用新的模板文字。您可以在此处了解有关它们的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

所以不要使用这个破碎的代码:

  var api = "http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=c873adc18574701f4fb0abe01d927819";

您可以这样做:

  var api= `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=c873adc18574701f4fb0abe01d927819`;