event.target
,但API文档没有提供那种交流的线索通过一切手段尝试。
如果这两个建议都不起作用,那么您可以利用闭包来保留 i
的副本,如下所示:
for(var i = 0; i< regionPolygons.length; i ++){
google.maps.event .addListener(regionPolygons [i],'click',(function(i){
return function(){
var polygon = regionPolygons [i];
//在这里用`多边形'
};
})(i));
}
或者,您可以使用相同的技术来保留对多边形对象的引用本身:
for(var i = 0; i< regionPolygons.length; i ++){
var p = regionPolygons [一世];
google.maps.event.addListener(p,'click',(function(polygon){
return function(){
//用`polygon`做点东西
};
})(p));
}
nett效应是相同的;在事件处理程序中,您最终会引用点击的多边形。
Hi I have a google maps polygons array named regionPolygons
. Now I want each time I click a polygon, my map will set its center at that of the polygon.
Here is how I implement it.
for (i = 0; i < regionPolygons.length; i++) {
google.maps.event.addListener(regionPolygons[i], 'click', function () {
// do the stuff, things seem ok here
}
}
Now whichever polygons I click, I am taken to the center of the last polygon.
How can I let Google maps now which polygon is clicked?
Thank you
Edit: My question a duplicate. It seems that copying the same code to the new function work. It seems that Javascript create new copy of the variable when it is passed from the main program to a sub program. Could any one help me explain about it?
解决方案
It would be sensible for Google to make the clicked polygon available within the event handler as this
or as event.target
but the API documentation gives no clues that that's actually done. By all means try.
If neither of those suggestions works, then you can exploit a closure to keep a copy of i
, as follows :
for(var i=0; i<regionPolygons.length; i++) {
google.maps.event.addListener(regionPolygons[i], 'click', (function(i) {
return function() {
var polygon = regionPolygons[i];
//do stuff here with `polygon`
};
})(i));
}
Alternatively, you could use the same technique to keep a reference to the polygon object itself :
for(var i=0; i<regionPolygons.length; i++) {
var p = regionPolygons[i];
google.maps.event.addListener(p, 'click', (function(polygon) {
return function() {
//do stuff here with `polygon`
};
})(p));
}
The nett effect is the same; inside the event handler, you end up with a reference to the clicked polygon.
这篇关于当JavaScript传递给一个函数时,是否会创建一个变量的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!