-1

我正在尝试做一些非常简单的事情,但是搜索结果是空的,由于某种原因我无法解决这个问题(我是 JS 初学者)。我正在尝试使用标签中的 onclick 关闭信息窗口。我知道您可以通过单击“x”来关闭它,但这样做的目的更深。

我的代码:

function placeMarker(location) {
    marker = new google.maps.Marker({
    position: location,
    map: map,
  });
  var infowindow = new google.maps.InfoWindow({
    content: "<a href='#' id='link' onclick='infowindow.close()'>Close</a>"
  });
  infowindow.open(map,marker);
}

这样的事情可能吗?谢谢

4

3 回答 3

2

assuming you may have multiple infoWindow-instances(with your current code this will happen when you call the function multiple times):

You'll need to use a Node instead of a string as content. When you do so, you'll be able to use a reference to the infowindow from within the function(a closure) and assign the click-function using addDomListener:

function placeMarker(location) {
    var marker = new google.maps.Marker({
               position: location,
               map: map,
             }),
        infowindow = new google.maps.InfoWindow(),
        content    = document.createElement('a');

    content.setAttribute('href','#');
    content.appendChild(document.createTextNode('close'));
    google.maps.event.addDomListener(content,'click',
                                     function(){infowindow.close();})
    infowindow.setContent(content);
    infowindow.open(map,marker);
}
于 2013-02-22T17:40:43.463 回答
1

是的,您的实现将按照您列出的方式工作,假设:

  1. 您使用单个通用信息窗口
  2. infowindow变量是全局的(在任何函数之外定义)
于 2013-02-22T16:51:22.690 回答
0

您不需要像您所拥有的那样的紧密链接onclick='infowindow.close()。InfoWindow 对象已经有一个“关闭”图标。X

为确保在任何给定时间只打开一个 InfoWindow,请将其设为单个全局对象并使用关联的标记作为参数打开:

//Global
var infowindow = new google.maps.InfoWindow({});

接着...

function placeMarker(location) {
    marker = new google.maps.Marker({
    position: location,
    map: map,
  });
  infowindow = new google.maps.InfoWindow({
    position: location,
    content: "Hello from this marker"
  });
  infowindow.open(map,marker);
 }
于 2013-02-22T16:39:04.437 回答