简体   繁体   English

无法从函数范围内访问变量

[英]Can't access variable from within a function's scope

I have this script to create google maps with markers template inside my Django project:我有这个脚本可以在我的 Django 项目中创建带有标记模板的谷歌地图:

<script>
  function initMap() {

    const shop = {
      lat: 45.0203018,
      lng: -88.318316
    };

    const map = new google.maps.Map(
      document.getElementById("map"), {
        zoom: 10,
        center: shop,
    });  
  
    const vehicles = {{ vehicles|safe }};
    for(i = 0; i < vehicles.length; i++){
      const pos = new google.maps.LatLng(vehicles[i]['lat'],vehicles[i]['lon']);
      const marker = new google.maps.Marker({
        position: pos,
        map: map,
        label: vehicles[i]['number'],
      }); 
    
      const id = vehicles[i]['truck']     
      marker.addListener("click", () => {
        console.log(id)
        window.location = "{% url 'invent:truck' id %}";
      });  
    };   
  };

  window.initMap = initMap;
</script>

But it doesn't see variable id inside the addListener function.但它在addListener函数中看不到变量id And if I put the variable inside the function it doesn't see the vehicles variable.如果我将变量放在函数中,它就看不到vehicles变量。 What am I doing wrong?我究竟做错了什么?

Figured it out:弄清楚了:

const id = vehicles[i]['truck']
const url = "{% url 'invent:truck' 1234 %}".replace(/1234/, id.toString());
marker.addListener("click", () => {
  window.location = url
});  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM