在页面加载时调用带参数的javascript函数

时间:2017-12-12 20:15:27

标签: javascript function google-maps parameters google-maps-markers



for(i = 0; i < locations.length; i++) {
  currentLocation = locations[i];

  var mapMarker = new google.maps.Marker ({
    position: locations[i][0],
    map: map,
    label: labels[i],
    title: locations[i][1],
    zoom: 18
  })

  mapMarkers.push(mapMarker);
  mapMarkers[i].addListener('click', markerClick(currentLocation)); 
}


function markerClick(location) {
  console.log("you clicked " + location)
}
&#13;
&#13;
&#13;

每次将函数markerClick添加到元素时都会调用它。如何才能使它只在单击元素时调用?我在另一个答案here中读到,遗漏()会解决这个问题,但我需要通过一个参数,我不知道该怎么做。谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

一个选项是让你的markerClick函数返回一个函数。

function markerClick(location) {
  return function(evt) {
    console.log("you clicked " + JSON.stringify(location));
  }
}

proof of concept fiddle

代码段

&#13;
&#13;
var locations = [
  [{lat: 42,  lng: -72}, "Here"],
  [{lat: 42.1,lng: -72.1}, "There"]
];
var mapMarkers = [];

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(42, -72),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  for (i = 0; i < locations.length; i++) {
    currentLocation = locations[i];

    var mapMarker = new google.maps.Marker({
      position: locations[i][0],
      map: map,
      // label: labels[i],
      title: locations[i][1],
      zoom: 18
    })

    mapMarkers.push(mapMarker);
    mapMarkers[i].addListener('click', markerClick(currentLocation));
  }
}

function markerClick(location) {
  return function(evt) {
    console.log("you clicked " + JSON.stringify(location));
  }
}
google.maps.event.addDomListener(window, "load", initialize);
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

添加侦听器时,您调用markerClick()函数而不是将其作为变量传递。以下是修复方法:

//using a separate function like this avoids some nasty 
//problems with callbacks and closures in for loops
function addMapMarkerClickListener( mapMarker, location ) {
 
   //we use an anonymous function as the listener
   mapMarker.addListener('click', function() {
      markerClick( location );
   });
}

for(i = 0; i < locations.length; i++) {
  currentLocation = locations[i];

  var mapMarker = new google.maps.Marker ({
    position: locations[i][0],
    map: map,
    label: labels[i],
    title: locations[i][1],
    zoom: 18
  })

  mapMarkers.push(mapMarker);

  addMapMarkerClickListener( mapMarkers[i], currentLocation );
}


function markerClick(location) {
  console.log("you clicked " + location)
}