【问题标题】:How Do I access a variable inside a variable inside a function in Javascript?如何在Javascript中访问函数内的变量内的变量?
【发布时间】:2018-04-04 17:41:30
【问题描述】:

当单击按钮时,我需要通过将 x 分配给 lat 对象来更改我的地图函数中的中心值。但是,我似乎无法弄清楚如何从我的 alertFunction 分配 map.center.lat = 43.138428。本质上,我在问如何从另一个函数引用一个对象,一个对象内部,一个函数内部。我在 Rails 内部工作。

<script>
//function to update my center
function alertFunction() {
    var x = document.getElementById("myInput").value;
    initMap();
    **Wrong Code**
    **// map.center.lat = 43.138428;**
};

//function to start map
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center:{lat: 41.138428, lng:-85.140239},
    });

【问题讨论】:

  • 如果我理解得很好,你只需要在你的initMap 函数中做return map; 并在你调用它时得到结果。

标签: javascript ruby-on-rails google-maps


【解决方案1】:

你的initMap函数应该返回一些东西,或者你可以使用一个参数来设置.lat

// the latter
function alertFunction() {
    var x = document.getElementById("myInput").value;
    initMap(43.138428);
    //      ^ pass latitude value
};

//function to start map
function initMap(latitude) {
//               ^ parameter
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center:{lat: latitude, lng:-85.140239},
      //           ^ from parameter
  });
}

// the former
function alertFunction() {
    var x = document.getElementById("myInput").value;
    var map = initMap();
    //        ^ initMap returns the map
    map.center.lat = 43.138428;
};

//function to start map
function initMap(latitude) {
 return new google.maps.Map(document.getElementById('map'), {
   zoom: 10,
   center:{lat: latitude, lng:-85.140239},
 });
}

【讨论】:

    【解决方案2】:

    他们在 Google Maps 文档中展示了它 - 您需要在函数之外声明您的“地图”变量,否则其他函数无法访问它。

        <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
    

    这样你的 initMap() 正在改变 initMap 函数之外的变量。

    【讨论】:

    • 天哪,我非常感谢你指出这一点。
    【解决方案3】:
    <script>
    //function to update my center
    function alertFunction() {
        var x = document.getElementById("myInput").value;
        var map = initMap();
        **Wrong Code**
        **// map.center.lat = 43.138428;**
    };
    
    //function to start map
      function initMap() {
        return map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10,
          center:{lat: 41.138428, lng:-85.140239},
        });
    

    重新运行地图,否则您必须使用全局变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 2018-12-02
      • 1970-01-01
      • 2017-06-01
      • 2015-04-29
      • 2013-02-17
      相关资源
      最近更新 更多