【问题标题】:Add listener after it has been removed on map marker在地图标记上删除监听器后添加监听器
【发布时间】:2016-04-20 07:27:38
【问题描述】:

创建我的Google map markers,时

我正在添加这样的事件侦听器 -

var infowindow = new google.maps.InfoWindow({
    content: 'Hi there from Alabama!'
});

google.maps.event.addListener(marker, 'mouseover', function () {
    infowindow.open(map, marker); // this displays the infowindow on mouseover
});

google.maps.event.addListener(marker, 'mouseout', function () {
    infowindow.close(); // this close the infowindow on mouseout
});

marker.addListener('click', function () {
    google.maps.event.clearListeners(marker, 'mouseout');
    // this removes the mouseout listener when the marker is clicked so that it stays
    // present after mouseout.
});

上述工作很有效,但我也希望能够在信息窗口关闭后重新添加mouseout 事件。

我尝试将它添加到我的函数中 -

google.maps.event.addListener(infowindow, 'closeclick', function () {
    google.maps.event.addListener(marker, 'mouseout');
    // when the info window is closed the mouseout event is reinstated
    // I also previously added an alert here to make sure it was hit!
});

这会创建标记 ok,但是在操作中,我可以单击标记 > mouseout 并让信息窗口保持存在 > 关闭信息窗口。所有期望的行为。

但是,当再次将鼠标悬停在标记上时,信息窗口会显示(如预期的那样),但在点击 mouseout 事件时,我得到 -

JavaScript runtime error: Unable to get property 'apply' of undefined or null reference

错误存在于 Google api JS 文件中,因此很难确定问题的根源是什么。如何在 infowindow 关闭时正确恢复 mouseout 事件?

【问题讨论】:

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


    【解决方案1】:

    目前,您在事件分配中有一个匿名函数:

    google.maps.event.addListener(marker, 'mouseout', function () {
        infowindow.close(); // this close the infowindow on mouseout
    });
    

    如果你创建一个命名函数,你可以像这样添加它:

    function mouseoutHandler() {
        infowindow.close(); // this close the infowindow on mouseout        
    }
    google.maps.event.addListener(marker, 'mouseout', mouseoutHandler);
    

    然后,你可以删除它...

    marker.addListener('click', function () {
        google.maps.event.clearListeners(marker, 'mouseout');
        // this removes the mouseout listener when the marker is clicked so that it stays
        // present after mouseout.
    });
    

    稍后,您只需像第一次一样重新添加事件 - 因为您有一个命名函数,所以您不会丢失声明!


    如果您在删除原始事件时仍然遇到错误,请might try being more specific:

    var listenerHandle = google.maps.event.addListener(marker, 'mouseout', mouseoutHandler);
    // later...
    google.maps.event.removeListener(listenerHandle);
    

    【讨论】:

    • 亚瑟,很好的回答,我完全理解我们的逻辑,但不幸的是(即使有更具体的减速)我仍然在鼠标悬停时遇到同样的未定义错误,还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2014-05-10
    相关资源
    最近更新 更多