如何使用Google地图事件侦听器来传递变量并提交表单 [英] How to use a Google map event listener to pass a variable and submit a form

查看:87
本文介绍了如何使用Google地图事件侦听器来传递变量并提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Google Maps v3演示库示例这里,这是一个矩形覆盖。

I'm following a Google Maps v3 demo gallery example here, which is a rectangle overlay. I modified the rectangle to make it clickable.

rectangle = new google.maps.Rectangle({
   map: map,
   clickable: true
});

然后我在矩形中添加了一个事件侦听器

Then I added an event listener to the rectangle

google.maps.event.addListener(rectangle, 'click', editSite);

,并且创建了一个方法来使表单提交,并且它正常工作。

and made a method to cause the form to submit, and it worked properly.

function editSite() {
    document.getElementById("siteSelection").value = 22;
    document.siteSelectionForm.submit();
}

接下来,我通过添加一个参数来改变editSite的签名。

Next, I changed editSite's signature by adding an argument.

google.maps.event.addListener(rectangle, 'click', editSite(22));

...

function editSite(siteId) {
    document.getElementById("siteSelection").value = siteId;
    document.siteSelectionForm.submit();
}

它停止正常工作。只要地图加载完成,表单就会提交,而之前我有机会点击矩形。这就好像该方法在页面重新加载期间一旦被添加到监听器就被调用。

It stopped working properly. The form would submit as soon as the map loaded, which was before I ever had the opportunity to click the rectangle. It's as though the method was invoked as soon as it was added to the listener during page reload.

我的目标是能够创建许多矩形,每个矩形,当点击,传递一个唯一的ID到editSite。我怎样才能做到这一点,并避免我创建的问题?

My goal is to be able to create many rectangles, each rectangle, when clicked, passing a unique ID to editSite. How can I do this and avoid the problem I've created?

推荐答案

这不会达到您的预期目标(并且缺少结尾),这是一个错字吗?) :

This won't do what you expect (and it is missing a closing ")", is that a typo?):

google.maps.event.addListener(rectangle, 'click', editSite(22);

不带参数的editSite是一个函数指针(在您的工作代码中):

the "editSite" without the arguments is a function pointer (in your "working" code):

google.maps.event.addListener(rectangle, 'click', editSite);

如果添加一个参数,它会立即执行并且返回值被用作事件发生时要执行的函数(不是你想要的在这种情况下)。你想用一个参数调用一个命名的函数,把它包装在一个匿名函数中:

if you add an argument, it gets executed immediately and the return value is used as the function to be executed when the event occurs (not what you want in this case). If you want to call a named function with an argument, wrap it in an anonymous function:

google.maps.event.addListener(rectangle, 'click', function() {
  editSite(22);
});

这篇关于如何使用Google地图事件侦听器来传递变量并提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆